简体   繁体   中英

SyntaxError: JSON.parse: unexpected character for null results

I know that the same topic is asked by several people, but I cannot find an answer for my problem from these questions. I have the following code,

$.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;
    }
}});

I am using php as back end. this code works fine in my local server and works fine in live server with the following 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"}]}}}

But for this json,

{"root": {"success":"2","message":"no results found","data":{"partners":[]}}}

in live server it shows,

SyntaxError: JSON.parse: unexpected character
var dataArray = JSON.parse(data);

I have tried to remove JSON.parse from my code but it shows

TypeError: dataArray.root is undefined
var array_locations=dataArray.root.data.locations;

Please help me to find a solution. Thanks.

So you shouldn't really need to be doing JSON.parse by hand - jQuery can do this for you if you tell it to expect JSON. It usually uses the Content-Type header in the return response but you can tell it to parse 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);
    }
});

By the way - I tried putting the JSON you specify there into the JSON.parse on the Chrome debug console and it worked fine. There's nothing wrong with that JSON.

Change your condition like this.

if(data.length >0){
    var dataArray = JSON.parse(data);

    if(typeof dataArray.root != undefined && dataArray.root.success == 1) {
        // Success
    }
    else {
       // Failure
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM