使用$ .getjson从外部源请求JSON. 200成功但是在哪里呢? [英] Request for JSON from externel source using $.getjson. 200 success but where is it?
问题描述
我正在尝试从openweathermap获取天气数据.该网址适用于我输入的坐标,在浏览器栏中输入网址时,我可以下载JSON.我正在尝试在我的页面中使用它.当我运行此代码时,在Firebug中,我可以看到HTTP请求获得了200成功代码,但是由于某种原因它没有打印响应.我不能正确使用getJSON吗?
I'm trying to get weather data from openweathermap. This url works with coordinates I put in, and I can download the JSON when I input the url the in the browser bar. I'm trying to get this working in my page. When I run this code, in Firebug I can see the HTTP request got the 200 success code, but it's not printing the response for some reason. Am I not using getJSON properly?
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读取.
You are trying to read cross domain JSON in a function which reads JSONP. Cross domain JSON reading is not possible.
改为尝试JSONP请求;通过添加回调
Try a JSONP request instead;, by appending a callback
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 }
JSON response is like this :
{ 'a':22 }
JSONP响应类似于:
myFunction({'a':22} )
,其中myFunction是作为callback
JSONP response is like :
myFunction({'a':22} )
, where myFunction was the value passed as callback
jQuery不需要回调函数的名称,但是需要在URL中提及callback
,以便它可以将其标识为JSONP请求.
jQuery does not need the name of the callback function, however needs callback
to be mentioned in the URL so that it can indentify it as a JSONP request.
JSONP
JSONP
如果URL包含字符串"callback =?" (或类似的定义, 服务器端API),则该请求将被视为JSONP.见 $ .ajax()中有关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.
这篇关于使用$ .getjson从外部源请求JSON. 200成功但是在哪里呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!