2012-06-04 87 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