我知道有几个人会问同一个主题,但我无法从这些问题中找到问题的答案。 我有以下代码,
$.post("show_search_results.php", {location_name: ""+location_name+"", key: ""+key+"", category_id: ""+category_id+"", page_number: ""+page_number+""}, function(data){
if(data.length >0){
var dataArray = JSON.parse(data);
var result_count=(dataArray.root.data.partners).length;
if(result_count > 0){
//block a;
}else if(s_limit==0){
//block b;
}else{
//block c;
}
}});
我使用php作为后端。这段代码在我的本地服务器上工作正常,并在使用以下json的实时服务器中正常工作。
{"root": {"success":"1","message":"Successfully retrieved data.","data":{"partners":[{"store_name":"Mega Mart (Readymade Brands)","store_address":"Next to SBI, Vyttila, Ernakulam","store_phone":"","item_name":"Festival of Young at 999","item_description":"Megamart celebrates the spirit of being young. Take home 4 groovy T-shirts or 2 stylish shirts or 3 women kurtas for just rupees 999.","item_offer":"999 Offer","offer_expiry":"2014-06-08","tag1":"T-shirt","tag2":"Dress","tag3":"Jeans","store_id":"a9e12c46-ee00-11e3-a5e4-bc305be6e93e"}]}}}
但对于这个json,
{"root": {"success":"2","message":"no results found","data":{"partners":[]}}}
在实时服务器中显示,
SyntaxError: JSON.parse: unexpected character
var dataArray = JSON.parse(data);
我试图从我的代码中删除JSON.parse,但它显示
TypeError: dataArray.root is undefined
var array_locations=dataArray.root.data.locations;
请帮我找一个解决方案。 感谢。
答案 0 :(得分:0)
所以你不应该手动做JSON.parse
- jQuery可以为你做这个,如果你告诉它期待JSON。它通常在返回响应中使用Content-Type标头,但您可以告诉它解析JSON:
$.post({
url: "show_search_results.php",
data: {
location_name: ""+location_name+"",
key: ""+key+"",
category_id: ""+category_id+"",
page_number: ""+page_number+""
},
dataType: "json",
success: function(data){
// do something with data here...
alert(data.root.message);
}
});
顺便说一句 - 我尝试将您指定的JSON放入Chrome调试控制台的JSON.parse
,它运行正常。 JSON没有错。
答案 1 :(得分:0)
像这样改变你的状况。
if(data.length >0){
var dataArray = JSON.parse(data);
if(typeof dataArray.root != undefined && dataArray.root.success == 1) {
// Success
}
else {
// Failure
}
}