使用jquery ajax将JSON发布到PHP
我有一个简单的PHP文件,解码我的json字符串,传递与ajax,并标记结果,但我不能保留$_POST
变量,为什么???
我尝试用fireBug进行检查,我可以看到POST请求被正确发送,当调用php脚本时,他回复Noooooooob给我,似乎设置了任何POST变量。
我想要的只是让我的数组=)
JSON.stringify
生成的JSON字符串:
[ { "id":21, "children":[ { "id":196 }, { "id":195 }, { "id":49 }, { "id":194 } ] }, { "id":29, "children":[ { "id":184 }, { "id":152 } ] }, ... ]
JavaScript的
$('#save').click(function() { var tmp = JSON.stringify($('.dd').nestable('serialize')); // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...] $.ajax({ type: 'POST', url: 'save_categories.php', dataType: 'json', data: {'categories': tmp}, success: function(msg) { alert(msg); } }); });
save_categories.php
如果你删除dataType: 'json'
,只是测试它,你的代码就可以了。
$('#save').click(function() { var tmp = JSON.stringify($('.dd').nestable('serialize')); // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...] $.ajax({ type: 'POST', url: 'save_categories.php', data: {'categories': tmp}, success: function(msg) { alert(msg); } }); });
dataType是json,所以jQuery发布了这个:
{"categories":"[{\"id\":21,\"children\":[{\"id\":196},{\"id\":195},{\"id\":49},{\"id\":194}]},{\"id\":29,\"children\":[{\"id\":184},{\"id\":152}]},...]"}
这不是标准的urlencoded,因此$ _POST为空。
您可以将数据设置为复杂的结构,jQuery将对其进行正确编码:
$('#save').click(function() { $.ajax({ type: 'POST', url: 'save_categories.php', dataType: 'json', data: $('.dd').nestable('serialize'), success: function(msg) { alert(msg); } }); });
在php中: $categories = json_decode(file_get_contents('php://stdin'));
试试这个:
$('#save').click(function() { var tmp = JSON.stringify($('.dd').nestable('serialize')); // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...] $.ajax({ type: 'POST', url: 'save_categories.php', dataType: 'json', data: 'categories=' + encodeURIComponent(tmp), success: function(msg) { alert(msg); } }); });
我改变了这一行:
data: 'categories=' + encodeURIComponent(tmp),
因为就是这样,你必须在那里写数据。 我测试了它,它的工作……
这对我有用,你可以尝试一下。 JavaScript的
$('#save').click(function() { $.ajax({ type: 'POST', contentType: 'application/json', url: 'save_categories.php', dataType: 'json', data: JSON.stringify({'categories': $('.dd').nestable('serialize')}), success: function(msg) { alert(msg); } }); });
你需要在save_categories.php上编写下面的代码$ _POST预先填充了表单数据。
要获取JSON数据(或任何原始输入),请使用php:// input。
$json = json_decode(file_get_contents("php://input")); $categories = $json->categories;