通过JQuery提交JSON数据ajax.post到PHP
即时通讯使用POST通过AJAX提交数据到PHP文件。 它工作得很好,只需提交的字符串,但现在我想用JSON和德$ C $提交我的JS对象C它PHP端。
Im submitting Data to a php file via AJAX using POST. It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
在控制台中,我可以看到,我的数据是正确的,但在PHP提交侧json_de code返回NULL。
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
我已经试过如下:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
和
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
警报只是检查一切正常......
The alert was just to check everything is alright...
和高雅往常一样串被正确地附和: - )
And yea usual string were echoed correctly :-)
您在第一code出了错在code是你必须已经使用这样的:
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
这是PHP报价手册
PHP://输入是一个只读的数据流,使您可以从请求体读取原始数据。
php://input is a read-only stream that allows you to read raw data from the request body.
由于你的情况,你的身体提交JSON,你必须从这个流中读取它。通常的方法 $ _ POST ['FIELD_NAME']
不会工作,因为后身体是不是在URLen codeD格式。
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name']
wont work, because the post body is not in an URLencoded format.
在第二部分中,您必须使用这样的:
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
更新
在请求中的内容类型应用程序/ JSON
,PHP不会解析请求,并给您的JSON对象 $ _ POST
,你必须自己从原始HTTP主体解析它。
When request has a content type application/json
, PHP wont parse the request and give you the JSON object in $_POST
, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");
.
如果你必须得到,使用 $ _ POST
,你将使其:
If you must get that using $_POST
you would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
然后在PHP做的:
And then in PHP do:
$json = json_decode($_POST['data']);