简体   繁体   中英

How can I parse this json string from an AJAX success function?

Can someone please help with parsing some data from a json string. Here is the JSON data:

data = "{\"centerLatitude\":-41.22766,\"centerLongitude\":174.812761,\"mapTypeId\":\"google.maps.MapTypeId.ROADMAP\",\"zoom\":18}"

In my AJAX code, I have the following code:

success: function (mapDetailsData) {
    var data = jQuery.parseJSON(mapDetailsData);
    alert(data.centerLatitude);
    alert(data.centerLongitude);
}

I am getting the following error in the console:

Uncaught SyntaxError: Unexpected token o

If I specify the JSON data as follows:

var data = jQuery.parseJSON('{\"centerLatitude\":-41.22766,\"centerLongitude\":174.812761,\"mapTypeId\":\"google.maps.MapTypeId.ROADMAP\",\"zoom\":18}');
alert(data.centerLatitude);
alert(data.centerLongitude);

The alert displays the correct data.

How do I need to write the ajax code to display the correct values of centerLatitude and centerLongitude ?

Thanks in advance.

Assuming that you set the datatype parameter to json (or leave it at the default setting and it recognises the JSON format by itself) then jQuery will automatically deserialise the response for you. The error you see is normally an indication that you are trying to parse twice. Try this:

success: function (mapDetailsData) {
    alert(mapDetailsData.centerLatitude);
    alert(mapDetailsData.centerLongitude);
}

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