通过JQuery ajax.post向PHP提交JSON数据
我使用POST通过AJAX将数据提交到php文件。 它只需提交字符串就可以正常工作,但现在我想用JSON提交我的JS对象并在PHP端解码它。
在控制台中,我可以看到,我的数据是正确提交的,但在PHP端,json_decode返回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']));
警报只是检查一切都没问题……
而通常的字符串是正确回应的:-)
在第一个代码中你的代码出错的地方是你必须使用它:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
引自PHP手册
php:// input是一个只读流,允许您从请求正文中读取原始数据。
因为在您的情况下,您正在正文中提交JSON,您必须从此流中读取它。 $_POST['field_name']
常用方法不起作用,因为post正文不是URLencoded格式。
在第二部分中,您必须使用此:
contentType: "application/json; charset=utf-8", url: "ajax/selectSingle.php?m=getAbsence", data: JSON.stringify({'Absence' : JSON.stringify(this)}),
更新 :
当请求具有内容类型application/json
,PHP不会解析请求并在$_POST
提供JSON对象,您必须自己从原始HTTP正文解析它。 使用file_get_contents("php://input");
检索JSON字符串file_get_contents("php://input");
。
如果你必须使用$_POST
获得它,你会做到:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
然后在PHP中执行:
$json = json_decode($_POST['data']);
单引号对php的json_encode
无效,对字段名和值都使用双引号。
对我来说,看起来你应该重新格式化你的AJAX对象。 url-property应该只是目标php文件的URL,任何需要发布的数据都应该是data-property中查询字符串的forms。 以下应该按预期工作:
this.getAbsence = function() { var strJSONData = JSON.stringify(this); alert(strJSONData); jQuery.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: 'ajax/selectSingle.php', data: 'm=getAbsence&Absence=' + strJSONData, success: function(data) { alert(data); } }); }
试试这个
var vThis = this; this.getAbsence = function() { alert(JSON.stringify(vThis)); jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "ajax/selectSingle.php?m=getAbsence", data: JSON.stringify(vThis), success : function(data){ alert(data); } }); }
编辑
我想我们也可以这样做!
var vThis = this; this.getAbsence = function() { alert(JSON.stringify(vThis)); jQuery.ajax({ type: "POST", dataType: "json", url: "ajax/selectSingle.php?m=getAbsence", data: vThis, success : function(data){ alert(data); } }); }
在PHP中
print_r($_POST);