我正在尝试从 openweathermap 获取天气数据。该 url 与我输入的坐标配合使用,当我在浏览器栏中输入 url 时,我可以下载 JSON。我正在尝试让它在我的页面上运行。当我运行此代码时,在 Firebug 中我可以看到 HTTP 请求获得了 200 成功代码,但由于某种原因它没有打印响应。我没有正确使用 getJSON 吗?
var url = "http://api.openweathermap.org/data/2.5/forecast?lat="+ position.coords.latitude +"&lon=" + position.coords.longitude;
$.getJSON(url, function(res) {
console.log(res);
});
最佳答案
您正在尝试在读取 JSONP 的函数中读取跨域 JSON。 无法跨域 JSON 读取。
尝试使用 JSONP 请求;通过附加回调
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" +
position.coords.latitude +"&lon=" + position.coords.longitude + "&callback=?" ;
$.getJSON(url, function(res) {
console.log(res);
});
JSON 响应如下:
{ 'a':22 }
JSONP 响应如下:
myFunction({'a':22} )
,其中 myFunction 是作为 callback
jQuery 不需要回调函数的名称,但需要在 URL 中提及callback
,以便将其识别为 JSONP 请求。
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
关于javascript - 使用 $.getjson 从外部源请求 JSON。 200成功但它在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323603/