地理定位问题's异步调用

Problems with Geolocation's asynchronous call

本文关键字:异步 调用 定位 问题      更新时间:2023-09-26

我正试图将我的位置作为Ajax请求发送
可能是由于地理定位的异步调用,它无法按预期工作。Geolocation的函数是在我的外部函数之后调用的,结果是data is empty答案。

$(document).ready(function() {
    $("button").click(function() {
        var data = "";
        if (...) { // if user wants to share their location
            function geo_success(position) {
                console.info("lat:" + position.coords.latitude + " Lot: " + position.coords.longitude);
                data = {
                    lat : position.coords.latitude,
                    lon : position.coords.longitude
                };
            }
            function geo_error() {
                alert("No position available.");
            }
            var geo_options = {
                enableHighAccuracy : true,
                timeout : 1000,
                maximumAge : 0
            };
            navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options);
        }
        if (...) { // if user doesn't want to share their location
            data = {
                a : "abc", // some other data
                b : "def"
            };
        }
        if (...) { // maybe a third option
            data = {
                b : "test", // some other data
                c : "some data"
            };
        }
        if (Object.keys(data).length > 0) {
            console.info("hier");
            $.ajax({
                method : "GET",
                url : "test.php",
                data : data, // finaly send data
                dataType : 'json',
                success : function(data) {
                    console.log(data)
                },
                error : function(data) {
                    console.error(data);
                }
            });
        } else {
            console.error("data is empty");
        }
    });
});
<input type="checkbox" id="box1" />
<button>ok</button>

我不能将Ajax请求放在geo_success中,因为需要首先定义data。在我的原始代码中(这里只是摘录),根据用户的选择,有几种可能的data
所以我只想要一个Ajax请求。

有什么可能的补救办法?

可能是由于地理定位的异步调用,它无法按预期工作。Geolocation的函数是在我的外部函数之后调用的,导致数据为空。

所以你的意思是这是一个异步调用?:

navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options);

如果是这种情况,那么我怀疑您可以为它提供回调函数,以便在操作完成时执行。和看起来你已经在这么做了。。。

function geo_success(position) {
    console.info("lat:" + position.coords.latitude + " Lot: " + position.coords.longitude);
    data = {
        lat : position.coords.latitude,
        lon : position.coords.longitude
    };
}
function geo_error() {
    alert("No position available.");
}

因此,如果您需要对异步操作的结果做出响应,只需将代码放在那些回调函数中即可。

异步意味着不同步。异步操作之后需要发生的任何事情都需要在该操作完成时由调用。在您的情况下,当您检查data时,它将始终为空,因为您在创建它时明确地将其设置为空字符串,而当时没有其他内容更新它。