使用 ajax 调用我将 json 数据包发送到 php 后端,但是由于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 似乎转换或收到错误的传入数据?