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

我正试图从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

如果URL包含字符串“callback =?” (或类似的,由服务器端API定义),请求被视为JSONP。 有关更多详细信息,请参阅$ .ajax()中有关jsonp数据类型的讨论。

追加这个?callback=? 到url,再试一次:

 $.getJSON(url + '?callback=?', function(res) { console.log(res); }); 

试试这个

  function buildQuery() { var str = "http://api.openweathermap.org/data/2.5/forecast?lat=27.175009&lon=78.041849"; return "select * from json where url ='" + str + "' "; } $.ajax({ url: 'http://query.yahooapis.com/v1/public/yql', data: { q: buildQuery(), format: "json" }, dataType: "jsonp", success: function (data) { alert(JSON.stringify(data)); }, error: function (data) { consol.log(data); } }); 

工作演示: –

http://jsfiddle.net/HWuDk/1/