使用ajax调用,我向php后端发送一个json数据包,但是json_decode
由于不清楚的原因而失败。有问题的php代码在这里:
$request = file_get_contents('php://input');
Logger::getInstance()->debug("Request: ".$request);
// The logger shows the following line after a sample submission:
// Request: prospectname=OMEGAK&teaserimg=kb.png&submit=Submit
$data = json_decode($request, true);
Logger::getInstance()->debug("Data: ".var_export($data,true));
// The logger shows the following line after a sample submission:
// Data: NULL
json的打包来自于各种类似的帖子,但我使用的是以下脚本(它只是试图发送表单提交的json编码的键值映射):
(function (){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var $blah = $('form').serializeObject();
// The $blah object reads like so at this point:
// {"prospectname":"OMEGAKB","teaserimg":"kb.png"}
var promise = $.ajax({
url: 'myform/save',
dataType: 'json',
data: $blah,
type: 'POST'
});
promise.done(function (result) {
alert("Success: "+result);
});
promise.fail(function (result) {
alert("Failure: "+result);
});
return;
});
});
})();
有人能解释我哪里出了问题吗?为什么php似乎转换或收到了错误的传入数据?
您实际上并没有发送JSON。您正在创建一个JavaScript对象并将其传递给$.ajax,后者将其转换为查询字符串并发布(它不会将其转换成JSON)。您可以使用JSON.stringify
将对象转换为JSON。
data: JSON.stringify($blah),
Is prospectname=OMEGAK&teaurimg=kb.png&submit=提交您所指的json?如果是,那就不是json。这是一个url字符串。http://php.net/manual/en/function.urldecode.php
dataType: 'json'
不会将您的数据转换为json。它告诉服务器您正在尝试发送json。
JSON
代表*javascript* object notation
。因此,当您使用jquery.serializeObject()时,实际上会得到一个对象作为回报。
直接从php.net:
<?php
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("Value for parameter "%s" is "%s"<br/>n", urldecode($param[0]), urldecode($param[1]));
}
}
?>
如果没有看到您的整个代码,就不能100%确定,但我相信,由于您最终执行的是"return"而不是"return false"或"e.preventDefault()",因此会触发标准的提交按钮行为,并且表单实际上是在没有ajax的情况下发布的。
我的猜测是ajax
方法中的url
不是php页面。将其更改为path.php
以测试此理论。处理PHP页面上的$data
,就像处理Associationve Array一样,然后处理echo
或print
,即json_encode()
中要返回到jQuery处理的结果,如:
echo json_encode($results);