0

我已经设置了一个函数和一个回调来检索有关天气警报的一些数据。由于某种原因,数据返回为“未定义”。我正在通过 json 获取数据,尽管我更愿意...获取 XML 和回调 json,但是获取和返回 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。为什么不重新调整正确的数据?

4

1 回答 1

0

“未定义”指的是回调函数,因为它不作为请求的一部分存在。

你告诉它你希望输出在 JSONP 中:

dataType: 'jsonp',

但是该 API 使用 JSON 响应(不包括回调)。

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

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

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

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

问题是,我在该 API 中看不到任何使用 zmw= 值的方法,因此您可能需要针对感兴趣的区域的解决方法。

于 2013-04-26T20:15:46.860 回答