2013-04-26 274 views
0

我已經設置了一個函數和回調來檢索有關天氣警報的一些數據。由於某些原因,數據以「UNDEFINED」的形式返回。我通過json獲取數據,儘管我更喜歡...獲取XML和回調json,但是獲取並返回json沒有問題。Json請求使用Wunderground API返回'UNDEFINED'

下面是我的代碼,但我已經把它放到jsfiddle中以使它更易於閱讀。

http://jsfiddle.net/seversides/G7Wr8/

的Javascript

$(function() { 
// Specify the location and Api key 
var apiKey = 'myapikey'; 
var location = 'zmw:00000.1.16172'; 

// Run the query (pull data from feed) 
var url = 'http://api.wunderground.com/api/' + apiKey + '/alerts/q/' + location +  '.json'; 

window['wCallback_3'] = function(data) { 
// Get any weather alerts 
var info = data.alerts; 
// Warning level and color 
$('#wWarning .wLevel').append('<TD>' + info.wtype_meteoalarm + '</TD>'); 
$('#wWarning .wColor').append('<TD>' + info.level_meteoalarm_name + '</TD>'); 

}; 

// Callback 
$.ajax({ 
url: url, 
dataType: 'jsonp', 
contentType: "application/json", 
cache: true, 
jsonpCallback: 'wCallback_3' 
}); 

}); 

HTML

<div id="wWarning"> 

<table class="wBox"> 
<h1 class="wLevel"></h1> 
<h1 class="wColor"></h1> 
</table> 

</div> 

當我運行它顯示數據作爲UNDEFINED的代碼。爲什麼它不重新調整正確的數據?

回答

0

「UNDEFINED」指的是回調函數,因爲它不作爲請求的一部分存在。

你告訴它你所要的輸出是JSONP在該行:

dataType: 'jsonp', 

但是,API與JSON響應(不包括回調)。

爲了與JSONP訪問它跨域(這是你在找什麼合適的協議),就需要使用自動完成API:

http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1

然後,設置回調與CB = myCallBack函數的GET字符串:

http://autocomplete.wunderground.com/aq?format=JSON&query=Anchorage&cb=myCallback

的問題是,我沒有看到任何方式API中使用ZMW =值,所以你可能需要一種解決方法的區域利益。

+0

嗨,謝謝你的回答。我所要求的是歐洲的警報功能http://www.wunderground.com/weather/api/d/docs?d=data/alerts我無法看到使用自動填充來請求此功能的方法。我的目標地址是唯一的,所以當我將名稱替換爲zmw值時,它會返回相同的數據。有沒有其他的方式來做到這一點? – ServerSideSkittles 2013-04-26 20:34:51

+0

嗯,這不是一個很好的後續,但我發現這個:http://stackoverflow.com/questions/5584923/a-cors-post-request-works-from-plain-javascript-but-why-not- with-jquery 它看起來像一個php解決方案,準備一個帶有標題的POST請求,但它假定服務器支持CORS請求。 – 2013-04-26 20:51:30