你已经告诉 jQuery 期待JSON-P http://en.wikipedia.org/wiki/JSONP#JSONP, not JSON http://json.org:
dataType: "jsonp"
...但结果是 JSON。 JSON-P 和 JSON 是根本不同的东西。以下是 JSON 响应示例:
{"foo": 42}
JSON-P 响应可能如下所示:
callback({"foo": 42});
or
callback({foo: 42});
If http://autocomplete.wunderground.com/a
与您的代码运行所在的文档不在同一来源,您将无法通过 ajax 从中检索 JSON,因为同源政策 http://en.wikipedia.org/wiki/Same_origin_policy(除非有问题的服务器支持CORS http://www.w3.org/TR/access-control/,允许您的请求来源,并且用户所使用的浏览器也支持 CORS)。我怀疑这就是您尝试使用跨域工作的 JSON-P 的原因。但问题是,server还必须支持 JSON-P。尽管format=jsonp
在 URL 中,服务器不是使用 JSON-P 响应,而是使用 JSON。
在评论中,您链接到他们的 API 文档 http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api,这表明他们do支持 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
事实上它确实有效:实例 http://jsbin.com/oqecik/1 | Source http://jsbin.com/oqecik/1/edit
The jsonp
argument 告诉 jQuery 使用什么 URL 参数来定义 JSON-P 回调的名称。默认为标准callback
但该 API 使用非标准参数。