简体   繁体   English

成功函数内部的AJAX回调

[英]AJAX callback inside sucess function

I'm trying to return a City from lat/long using a callback from AJAX, but the return is undefined although the AJAX is calling the callback with correct value (city). 我正在尝试使用AJAX的回调从经纬度返回城市,但是返回值是不确定的,尽管AJAX正在使用正确的值(城市)调用回调。

I've been reading How do I return the response from an asynchronous call? 我一直在阅读如何从异步调用返回响应? but i am tryng to figure out why the City is still being returned and written as undefined . 但我想弄清楚为什么仍要返回城市并将其写为undefined

Here's the whole code: 这是整个代码:

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

GetCity doesn't return a value, that's why it's always coming back as undefined . GetCity不返回值,这就是为什么它总是返回undefined Asynchronous programming takes time to get the trick of, but in general you usually don't usually use the returns from functions, you're usually passing around callbacks. 异步编程需要花一些时间才能掌握窍门,但通常来说,通常您通常不使用函数的返回值,而通常会传递回调。 The tricky bit for what you're trying to do is that you need to keep your element in proper scope so that you can set the inner text in the callback . 要尝试执行的操作比较棘手的一点是,您需要将元素保持在适当的范围内,以便可以在回调中设置内部文本。 The code below gives you an example using an anonymous function instead of a named function callback. 下面的代码为您提供了一个使用匿名函数而不是命名函数回调的示例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM