Json 请求'UNDEFINED'使用 Wunderground API 返回



我设置了一个函数和一个回调函数来检索有关天气警报的一些数据。由于某些原因,数据返回为'UNDEFINED'。我通过json获取数据,虽然我更喜欢。fetch XML和callback json,但是fetch和return json是可以的。

下面是我的代码,但我把它放在一个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。为什么它没有返回正确的数据?

"UNDEFINED"指的是回调函数,因为它不存在作为请求的一部分。

你告诉它你想在JSONP中输出:

dataType: 'jsonp',

但是该API正在响应JSON(不包括回调)。

为了使用JSONP跨域访问它(这是您正在寻找的正确协议),您需要使用AutoComplete API:

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

然后,在GET字符串中使用cb=myCallback设置回调:

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

问题是,我在该API中没有看到使用zmw= values的任何方法,因此您可能需要针对感兴趣的区域使用变通方法。

最新更新