我正在尝试解析这个 JSON 字符串:
{ "RESULTS": [ { "name": "Thessaloniki GR", "type": "Sailing", "l": "/sailing-weather/beach:Porto%20Carras%20Marina 45904" }, { "name": "Thessaloniki, Greece", "type": "city", "c": "GR", "zmw": "00000.1.16622", "tz": "Europe/Athens", "tzs": "EET", "l": "/q/zmw:00000.1.16622" } ] }
检索自 here
这是我的片段:
$(document).ready(function () {
$("#w11").autocomplete({
source: function (a, b) {
$.ajax({
url: "http://autocomplete.wunderground.com/aq",
dataType: "jsonp",
data: {
format: "jsonp",
query: a.term
},
success: function (a) {
for (i in data.RESULTS) {
console.log(data.RESULTS);
}
}
})
}
});
});
这给了我一个错误 Uncaught SyntaxError: Unexpected token :
在第一行,即 { "RESULTS": [
如何解析 JSON 结果?
最佳答案
你已经告诉 jQuery 期待 JSON-P ,不是JSON :
dataType: "jsonp"
...但结果是 JSON。 JSON-P 和 JSON 是根本不同的东西。下面是一个 JSON 响应示例:
{"foo": 42}
JSON-P 响应可能如下所示:
callback({"foo": 42});
或
callback({foo: 42});
如果 http://autocomplete.wunderground.com/a
与您的代码运行所在的文档不在同一源,您将无法通过 ajax 从中检索 JSON因为Same Origin Policy (除非相关服务器支持 CORS ,允许您的请求来源,并且用户所使用的浏览器也支持 CORS)。我怀疑这就是您尝试使用跨域工作的 JSON-P 的原因。但问题是,服务器也必须支持 JSON-P。尽管 URL 中包含 format=jsonp
,但服务器并未使用 JSON-P 进行响应,而是使用 JSON 进行响应。
在评论中,您链接到 their docs for that API ,这表明他们确实支持 JSON-P,只是在 URL 中使用非标准参数名称(cb
而不是更常见的 callback
)。
所以这应该可行(我还解决了我在问题评论中提到的代码的问题):
$.ajax({
url: "http://autocomplete.wunderground.com/aq",
dataType: "jsonp",
jsonp: "cb", // <================= New bit is here
data: {
format: "json", // <=== "json" not "jsonp" according to the docs, but I think the "cb" argument overrides it anyway
query: a.term
},
success: function (data) { // <=== `data`, not `a`
var i;
for (i in data.RESULTS) {
console.log(data.RESULTS[i]); // <=== Use [i] here
}
}
}); // <=== Semicolon was missing
事实上它确实有效:Live Example | Source
jsonp
参数告诉 jQuery 使用哪个 URL 参数来定义 JSON-P 回调的名称。默认值是标准回调
,但该 API 使用非标准参数。
关于jquery - 意外 token : when trying to parse a JSON string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899767/