Open weather map API , couldn't get JSON, but getting JSONP and couldnt make asynchronous call

后端 未结 1 1728
梦如初夏
梦如初夏 2021-02-10 16:21

Am getting longitude and latitude values from google\'s webserivce and passing the values to open weather map api to get the temperature values. Code below

funct         


        
1条回答
  •  孤独总比滥情好
    2021-02-10 17:16

    If you're using JQuery then you could use a defer and promise. Something like this:

    function getWeatherData(latitude, longitude) {
        var temperature = 0;
        var dfd = $.Deferred();
        var url = "http://api.openweathermap.org/data/2.5/weather?lat=";
        url += latitude;
        url += "&lon=";
        url += longitude;
        url += "&cnt=1";
        $.ajax({
            type: "POST",
            dataType: "jsonp",
            url: url + "&callback=?",
            async: false,
            success: function (data) {
                temperature = data.list[0].main.temp;
                alert(temperature);
                dfd.resolve(temperature);
            },
            error: function (errorData) {
                alert("Error while getting weather data :: " + errorData.status);
            }
        });
        return dfd.promise();
    }
    

    This will cause it to return the value once temperature has been resolved through the ajax call. I was using a weather API and had this same exact problem.

    0 讨论(0)
提交回复
热议问题