有人可以帮忙从 json 字符串中解析一些数据吗?这是 JSON 数据:
data = "{\"centerLatitude\":-41.22766,\"centerLongitude\":174.812761,\"mapTypeId\":\"google.maps.MapTypeId.ROADMAP\",\"zoom\":18}"
在我的 AJAX 代码中,我有以下代码:
success: function (mapDetailsData) {
var data = jQuery.parseJSON(mapDetailsData);
alert(data.centerLatitude);
alert(data.centerLongitude);
}
我在控制台中收到以下错误:
Uncaught SyntaxError: Unexpected token o
如果我指定JSON数据如下:
var data = jQuery.parseJSON('{\"centerLatitude\":-41.22766,\"centerLongitude\":174.812761,\"mapTypeId\":\"google.maps.MapTypeId.ROADMAP\",\"zoom\":18}');
alert(data.centerLatitude);
alert(data.centerLongitude);
警报
显示正确的数据。
我需要如何编写 ajax 代码来显示 centerLatitude
和 centerLongitude
的正确值?
提前致谢。
最佳答案
假设你将 datatype
参数设置为 json
(或者保留默认设置,它自己识别 JSON 格式)那么 jQuery 将自动反序列化响应为你。您看到的错误通常表明您正在尝试解析两次。试试这个:
success: function (mapDetailsData) {
alert(mapDetailsData.centerLatitude);
alert(mapDetailsData.centerLongitude);
}
关于javascript - 如何从 AJAX 成功函数解析此 json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30454183/