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

时间:2013-04-26 19:43:28

标签: javascript xml json wunderground

我已经设置了一个函数和一个回调来检索有关天气警报的一些数据。出于某种原因,数据以'未定义'的形式返回。我通过json获取数据虽然我更喜欢...获取XML和回调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。为什么不重新调整正确的数据?

1 个答案:

答案 0 :(得分:0)

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

您告诉它您希望输出在行中的JSONP中:

dataType: 'jsonp',

但该API正在使用JSON进行响应(不包括回调)。

为了使用JSONP(这是您正在寻找的正确协议)跨域访问它,您需要使用自动完成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 =值,因此您可能需要针对感兴趣的区域进行解决方法。