【发布时间】:2014-01-08 08:26:28
【问题描述】:
我无法在 ajax 成功时解析多对象 JSON。但是,当我收到单个对象 JSON 时,我可以。
Ajax 调用
$.ajax({
url: "ajax/filter.php",
dataType: "JSON",
type: "POST",
data: {
category: $categoryArr,
brand: $brandArr,
occasion: $occasionArr,
colour: $colourArr,
price_min: $price_min,
price_max: $price_max
},
success: function(data) {
data = JSON.parse(data);
$("#result").html(data["name"]);
}
});
单个对象 JSON 的 PHP 代码
$products = R::findOne('products', $filterString, $filterArray); //returns single row from db
if (!empty($products)) {
echo $products;
} else {
echo "No Products are available for this search criteria";
}
结果:{"id":"1","name":"Malbari-Product1","brand_id":"1","category_id":"1","colour_id":"2","occasion_id ":"2","price":"599","discount":"10","small_img":"images/products_small/1.png","big_img":"images/products_big/1.jpg", "seller_id":"1"}
多对象 JSON 的 PHP 代码
$products = R::find('products', $filterString, $filterArray); //returns multiple rows from db
if (!empty($products)) {
echo $products;
} else {
echo "No Products are available for this search criteria";
}
结果:{"id":"1","name":"Malbari-Product1","brand_id":"1","category_id":"1","colour_id":"2","occasion_id ":"2","price":"599","discount":"10","small_img":"images/products_small/1.png","big_img":"images/products_big/1.jpg", "seller_id":"1"} {"id":"10","name":"Malbari-Product6","brand_id":"2","category_id":"1","colour_id":"1" ,"occasion_id":"5","price":"350","discount":null,"small_img":"images/products_small/6.png","big_img":"images/products_big/6.jpg" ,"seller_id":"2"}
我想,如果有多个对象,我实际上得到的是单个字符串而不是多个对象 JSON。
请帮忙。
【问题讨论】:
-
JSON.parse在这里不需要。dataType: "JSON",应该告诉 jQuery 为你做这件事。 -
您能否粘贴一些示例返回数据集,以便我们了解我们正在查看的内容?
-
返回多个对象时需要在响应中运行循环
-
@RocketHazmat:没错,但这个技巧似乎只在单个物体的情况下有效。它将多个对象 JSON 视为字符串!
-
我不知道您的
$products变量包含什么,但至少您的错误消息不是有效的 json。我建议你收集所有信息,最后只做一个echo json_encode($all_info);
标签: javascript php jquery ajax json