How to use JSONP GET request with the OpenWeatherAPI?

主宰稳场 提交于 2019-12-10 11:23:20

问题


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.


回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/14567402/how-to-use-jsonp-get-request-with-the-openweatherapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!