将json数据发送到服务器jquery.ajax
不幸的是,另一个json相关问题……
考虑以下json
[{"details":{ "forename":"Barack", "surname":"Obama", "company":"government", "email":"bigcheese@whitehouse.com", "files": [{ "title":"file1","url":"somefile.pdf" }, { "title":"file2", "url":"somefile.pdf" }] } }]
我需要将这些数据发送到我的服务器上的PHP脚本,然后在服务器上与它进行交互,但不知道如何。
我是通过jquery.ajax发送它并将其发送正常(没有错误消息)并inheritance代码。 (newJson是我完全按照上面创建的json对象)
$.ajax({ type: "POST", url: "test.php", dataType: 'json', data: newJson, success: function(msg) { alert(msg); }, error: function(jqXHR, textStatus) { alert(textStatus); } });
所以在我的PHP脚本中,到目前为止我只想将内容回显为成功警报中显示的字符串
但这只是给我一个解析错误..所以任何想法你都很棒的人?
你必须有一个键/值对来接收PHP中的数据$_POST[key]
。 发送你拥有的数组本身并不是最好的方法,因为你已经有了对象的结构
我会解开外部数组,因为你只在其中发送一个对象
然后对象看起来像
{"details":{ "forename":"Barack", "surname":"Obama", "company":"government", "email":"bigcheese@whitehouse.com", "files": [{ "title":"file1","url":"somefile.pdf" }, { "title":"file2", "url":"somefile.pdf" }] } }
在php中将收到$_POST['details']
。 不要转换为JSON,只需将整个对象传递给$.ajax data
属性。
如果你从ajax获得parserror
,就是在接收端,听起来像是从php获得500个错误或者没有按照dataType
预期发回json
首先,原始JSON字符串格式错误。 尝试
{ "details":{ "forename":"Barack", "surname":"Obama", "company":"government", "email":"bigcheese@whitehouse.com", "files": [ { "title":"file1","url":"somefile.pdf" }, { "title":"file2","url":"somefile.pdf"} ] } }
其次,发送给PHP的数据已经解析为数组,但不是JSON。 要回显,必须使用json_encode将数组转换回JSON字符串
echo json_encode($_POST); exit;
由于您没有将JSON作为字段传递,因此您可以: