jQuery $ .post处理JSON响应
我无法弄清楚如何从jQuery $ .post()请求中正确读取我的JSON响应。
在下面的jQuery代码中,我根据我用作关键字的相应“color_entry_id”填充DOM中元素的关联数组字符串:
var image_links = {}; $(this).find('input[name="color_id"]').each(function() { var color_entry_id = $(this).val(); var image_link = $(this).parent().find('input[name="edit_image"].' + color_entry_id).val(); image_links[color_entry_id] = image_link; });
然后我发出POST请求,发送我的“image_links”数组:
$.post( "test.php", { id: product_id, "images[]": jQuery.makeArray(image_links) }, function(data) { var response = jQuery.parseJSON(data); $.each(response.images, function(index, item) { alert(item); }); } );
另外,如上所示,我尝试循环遍历响应数组并输出每个项目,我想成为一个字符串,但我只得到“[object Object]”作为警告值。 我不知道如何让它显示我想要显示的字符串!
这是test.php的PHP代码:
以下是DOM的相关部分:
Image Link:
我想知道是否我在PHP端错误地进行JSON编码,或者我只是在jQuery中错误地循环响应。 任何帮助深表感谢!!
好吧..你从post里回来的数据对象是: {"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/223"}]};
如果您更改提醒,您将找到您要查找的值:
$.post( "test.php", { id: product_id, "images[]": jQuery.makeArray(image_links) }, function(data) { var response = jQuery.parseJSON(data); var images = response.images[0]; for (var i in images){ alert(images[i]); } } );
$ .post默认需要xml,您需要指定响应格式
$.post( "test.php", { id: product_id, images : jQuery.makeArray(image_links) }, function(response) { // Response is automatically a json object for(var i = 0; i < response.images.length; i++) { alert(response.images[i]); } }, 'json' // <-- HERE );
另外,请考虑在php脚本中添加内容类型标头
一个非常基本的例子是:
$.post('test.php', {"id": 42}, function (json) { console.log(json); }, 'json');
PHP示例
$number = rand(1,$_POST["id"]); return print json_encode($number);