简体   繁体   English

如何从AJAX成功函数解析这个json字符串?

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

Can someone please help with parsing some data from a json string. 有人可以帮助解析json字符串中的一些数据。 Here is the JSON data: 这是JSON数据:

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

In my AJAX code, I have the following code: 在我的AJAX代码中,我有以下代码:

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 未捕获的SyntaxError:意外的令牌o

If I specify the JSON data as follows: 如果我指定JSON数据如下:

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. alert显示正确的数据。

How do I need to write the ajax code to display the correct values of centerLatitude and centerLongitude ? 如何需要编写Ajax代码以显示正确的价值观centerLatitudecenterLongitude

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. 假设您将datatype参数设置为json (或将其保留为默认设置并且它自己识别JSON格式),那么jQuery将自动为您反序列化响应。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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