How to use JSONP GET request with the OpenWeatherA

2019-05-28 14:00发布

I am trying to use the OpenWeatherAPI to perform get JSONP data using a JQuery get request. I have structured my query like this:

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');
});

I get the following error message:

SyntaxError: invalid label

However, the data is being returned as I can click on it in Firebug and it gives me the expected results. I am performing this all on the client-side so perhaps I have a basic mistake on my JSONP request. Searching on this topic also suggested that the returned data may be in JSON form and not JSONP, but I am unsure of what the difference is.

2条回答
干净又极端
2楼-- · 2019-05-28 14:27

If you are using jQuery, you can use the built in JSONP functionality to handle the callback for you. Just use $.ajax instead, as so:

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/

reference: http://api.jquery.com/jQuery.ajax/

查看更多
疯言疯语
3楼-- · 2019-05-28 14:40

It looks like the api say that you should use callback instead of jsoncallback as parameter in the url.

Descriped in the table here

callback - functionName for JSONP calback. http://en.wikipedia.org/wiki/JSONP

Follwing code works for me:

$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });
查看更多
登录 后发表回答