ajax调用返回值,但变量为null

ajax call returns value but variable is null

本文关键字:变量 null 调用 返回值 ajax      更新时间:2023-09-26

我正试图从这里获得天气预报。这很好,我明白我的价值。如果我做一个普通的ajax调用,它工作得很好。

但是:

function Weather() {
    var self = this,
        weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=',
        value = null;
    function getWeatherForCity(id) {
        $.ajax({
            url: weatherUrl + id,
            async: false,
            success: function (data) {
                console.log(data);
                value = data;
            }
        });
    }
    self.getWeatherForCity = function (id) {
        var cast = value;
        console.log(cast);
        return cast;
    };
}

呼叫:

        weather = new Weather();
        console.log(weather.getWeatherForCity('2878234'));

如果我通过这些函数进行调试,我会在success回调函数中得到好的结果,但强制转换变量为null,就像它从未被触摸过一样?

有人能给我解释一下吗?

问题。您的问题是,您从不调用本地getWeatherForCity函数。因此它从不更改value变量。这应该解决它:

self.getWeatherForCity = function (id) {
    getWeatherForCity(id);
    return value;
};

更好的方法。看来您已经意识到使用async: false不是理想的解决方案。在这种情况下,我会建议你更好的选择。

function Weather() {
    var self = this,
        weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=';
    function getWeatherForCity(id) {
        return $.get(weatherUrl + id);
    }
    self.getWeatherForCity = function (id) {
        return getWeatherForCity(id);
    };
}
var weather = new Weather();
weather.getWeatherForCity('2878234').then(function(data) {
    console.log(data);
});

使用异步代码可以使UI在请求期间不冻结。promise的使用使代码更加干净和全面。

您有两个不同的getWeatherForCity()函数——一个是方法,另一个是私有函数(位于闭包内)。你从不调用私有函数,它实际上起作用。

function Weather() {
    var self = this,
        weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=',
        value = null;
    function getWeatherForCity(id) {
        $.ajax({
            url: weatherUrl + id,
            async: false,
            success: function (data) {
                console.log(data);
                value = data;
            }
        });
    }
    self.getWeatherForCity = function (id) {
        getWeatherForCity(id); // here
        var cast = value;
        console.log(cast);
        return cast;
    };
}

您还可以研究$.when方法,该方法在继续之前等待Ajax调用完成:

http://api.jquery.com/jquery.when/

你会这样使用它:

$.when(getWeatherForCity([pass the parameter here])).done(function(){
    // do stuff here after the method is finished
});

您还需要为Ajax函数使用返回,如下所示:

return $.ajax({
        url: weatherUrl + id,
        async: false,
        success: function (data) {
            console.log(data);
            value = data;
        }
    });