如何在OpenWeathermAP中使用JSONP GET请求?

时间:2013-01-28 17:11:59

标签: jquery json callback jsonp

我正在尝试使用OpenWeatherAPI使用JQuery get请求执行获取JSONP数据。我已经构建了我的查询:

function getWeather(callback) {
    var weather = 'http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&jsoncallback=?';
    jQuery.getJSON(weather, callback);
}

// get data:
getWeather(function(data){
    console.log('weather data received');
});

我收到以下错误消息:

  

SyntaxError:无效标签

然而,数据正在返回,因为我可以在Firebug中点击它,它给了我预期的结果。我在客户端执行此操作,所以也许我的JSONP请求有一个基本错误。搜索此主题还表明返回的数据可能是JSON形式而不是JSONP,但我不确定它们之间的区别。

2 个答案:

答案 0 :(得分:7)

如果您使用的是jQuery,则可以使用内置的JSONP功能来处理回调。只需使用$ .ajax,如下所示:

function getWeather(callback) {
    var weather = 'http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.26612&cnt=10';
    $.ajax({
      dataType: "jsonp",
      url: weather,
      success: callback
    });
}

// get data:
getWeather(function (data) {
    console.log('weather data received');
    console.log(data.list[0].weather[0].description);
});

jsFiddle:http://jsfiddle.net/wCjW3/1/

参考:http://api.jquery.com/jQuery.ajax/

答案 1 :(得分:3)

看起来api说你应该使用callback代替jsoncallback作为网址中的参数。

Descriped in the table here

  

回调 - JSONP calback的functionName。 http://en.wikipedia.org/wiki/JSONP

Follwing代码适用于我:

$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });