成功函数内的AJAX回调

时间:2015-08-06 19:15:45

标签: javascript jquery ajax return

我尝试使用来自AJAX的回调从lat / long返回一个City,但返回是 undefined ,尽管AJAX正在使用正确的值(city)调用回调。 / p>

我一直在阅读How do I return the response from an asynchronous call?,但我正在尝试弄清楚为什么仍然会将城市归还并写为 undefined

这里是整个代码:

function getLocation(id) {
    x = document.getElementById(id);
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function showPosition(position) {
            x.innerText = GetCity(position.coords.latitude, position.coords.longitude, returnCity);
        });
    } else {
        this.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function returnCity(result) {
    return result;
}

function GetCity(lat, long, callback) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&sensor=false",
        data: {},
        success: function (data) {
            var city;
            $.each(data['results'], function (i, val) {
                $.each(val['address_components'], function (i, val) {
                    if (val['types'] == "locality,political") {
                        if (val['long_name'] != "") {
                            city = val['long_name'];
                        } else {
                            city = "N/A";
                        }
                    }
                });
            });
            callback(city);
        },
        error: function () {
            alert('error');
        }
    });
}

1 个答案:

答案 0 :(得分:0)

GetCity没有返回值,这就是为什么它总是以undefined的形式返回。异步编程需要时间才能得到诀窍,但一般来说,你通常不会使用函数的返回,你通常会绕过回调。您尝试做的最棘手的一点是,您需要将元素保持在适当的范围内,以便可以在回调中设置内部文本。下面的代码给出了一个使用匿名函数而不是命名函数回调的示例。

function getLocation(id) {
    x = document.getElementById(id);
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function showPosition(position) {
            GetCity(position.coords.latitude, position.coords.longitude, function(result) {
                x.innerText = result;
            });
        });
    } else {
        this.innerHTML = "Geolocation not supported by browser.";
    }
}

function GetCity(lat, long, callback) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&sensor=false",
        data: {},
        success: function (data) {
            var city;
            $.each(data['results'], function (i, val) {
                $.each(val['address_components'], function (i, val) {
                    if (val['types'] == "locality,political") {
                        if (val['long_name'] != "") {
                            city = val['long_name'];
                        }
                        else {
                            city = "N/A";
                        }
                    }
                });
            });
            callback(city);
        },
        error: function () { alert('error'); }
    });
}