javascript - 使用 $.getjson 从外部源请求 JSON。 200成功但它在哪里?

标签 javascript jquery

我正在尝试从 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/

相关文章:

javascript - Linq.js Enumerable.from()

javascript - 数组映射 react 组件调用子函数

javascript - Jquery fadeIn fadeOut 在 IE8 中不工作,但在 chrome,firefox 中工作

javascript - 如何创建一个空的 HTML anchor ,以便在我单击它时页面不会显示 "jump up"?

javascript - Jquery 附加项目点击功能不起作用

javascript - 加载在同一个 div 中打开的超链接

javascript - JavaScript 中的数组和字符串

javascript - react 热加载程序 3

javascript - 处理复选框列表并选择标签

javascript - 如何将 JavaScript 添加到 ASP.NET MVC View ?