2012-06-04 89 views
0

我想捕捉天气信息。我试图用jQuery来做到这一点。所以这里是我的代码:jQuery雅虎天气API调用失败

$(document).ready(function(){ 
var weatherURL = 'http://weather.yahooapis.com/forecastjson?w=20066287&u=c&callback=?'; 
$.getJSON(weatherURL, function(data){ 
    //console.log('done'); 
}); }); 

看来这是行得通的。但它输出我

Uncaught SyntaxError: Unexpected token :

我认为它的JSON验证问题。但是所有在线的JSON验证工具都通过了测试。

+0

你得到JSON回来,没有JSONP 。 http://weather.yahooapis.com/forecastjson?w=20066287&u=c&callback=foobar –

+1

现在检查这个http://joynag.net/demos/weather,JSON是好的,并在PHP中正确解析,但JS不是能够解析这一点。但jsonlint.com说这是有效的。所以一个解决方法可以是使用PHP获取并从后端传递给JS。我模拟了一个Ajax请求,它工作正常。 –

回答

0

看来API会返回JSON,而不是JSONP数据;的getJSON会自动尝试解析它作为JSONP是有URL中的回调查询:

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.

http://api.jquery.com/jQuery.getJSON/


试试这个:

$(document).ready(function(){ 
    var weatherURL = 'http://weather.yahooapis.com/forecastjson?w=20066287&u=c'; 
    $.ajax({ 
     url: weatherURL, 
     dataType: 'json', 
     success: function(data) { 
     //console.log('done'); 
     } 
    }); 
}); 
+0

它不能解决问题,请点击http://jsfiddle.net/joycse06/AmhyF/。 'dataType:'json''也会尝试解析它 –

+0

同样的错误:未捕获的SyntaxError:意外的令牌:forecastjson:1 – tuna

+0

它似乎也没有'callback':http://weather.yahooapis.com/forecastjson? w = 20066287&u = c您可以尝试更新的代码吗? – Jeroen