jQuery将json数据发布到PHP文件

jQuery将json数据发布到PHP文件

本文介绍了jQuery将json数据发布到PHP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个click事件,其中编写了一个 json数据,然后我想将其发布到PHP文件中进行处理.但是出了点问题.现在,我的PHP文件已简化如下:

I have a click event where I compose a json data, then I want to POST it to a PHP file for processing. But something goes wrong.My PHP file is simplified for now looking like this:

<?php
header('Content-Type: application/json');
 var_dump($_POST);
?>

并且POST-ing的代码如下:

And the code for POST-ing looks like this:

// myarray is: var myarray = new Array();
// and it gets populated above this code

var strObj = JSON.stringify(myarray);
alert(strObj); // so far I get the alert containing valid JSON text
$.ajax ({
  type:"POST",
  url:"proces.php",
  contentType: "application/json",
  dataType: "json",
  async: false,
  data: strObj,
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});

因此,当我单击按钮时,我收到包含JSON字符串的警报(看起来不错),然后我收到警告说错误",并且当我在控制台中检查proces.php的响应时,我看到的只是:

So when I click the button, I receive the alert containing the JSON string (looks fine), then I get the alert saying "error", and when I check the console for the response of proces.php all I see is:

array(0) {
}

我在做什么错了?我该怎么做才能解决问题?

What am I doing wrong? What can I do to make it right?

推荐答案

我自己得到了答案.似乎可以解决问题:

I got an answer on my own. Seems to do the trick:

$.post("proces.php", {json: JSON.stringify(myarray)}, function(data){alert(data);});

我的意思是,我没有收到警报(数据); (可能是因为我没有从php文件返回JSON),但是在PHP中,我现在可以看到json数据.

I mean, I do not get the alert(data); (probably because I do not return a JSON back from php file) but in the PHP I can see the json data now.

这篇关于jQuery将json数据发布到PHP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:45