gpt4 book ai didi

javascript - HTML5/Javascript 地理位置 : Pass data to callback function -or- suspend async call (with promises)?

转载 作者:行者123 更新时间:2023-12-02 17:46:53 25 4
gpt4 key购买 nike

我需要获取 HTML5/Javascript 地理位置以将位置数据传递给 ajax 调用以存储在数据库中。我遇到的问题是(1)地理位置调用是异步的,(2)变量范围让我困惑。

我正在考虑两种方法,但我不确定如何让其中一种方法正常工作。以下是方法:

需要从下面的代码中的.click传递this值:

jQuery("div#normal .m_action").click(function() {
navigator.geolocation.getCurrentPosition(storeAction(action), errorAction);
});

function storeAction(action, position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;

jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id, lat: latitude, long: longitude }
}).done(function(result) {
if(result == "error") {
alert("Error in ajax action.php file");
} else {
jQuery(action).removeClass("m_action");
jQuery(action).html(result);
}
}).fail(function(result) {
alert("There was an error with the ajax call itself")
});
}

或者我可以尝试推迟 ajax 调用,直到 getCurrentPosition 调用完成之后。下面的代码只是我所讨论内容的粗略估计,尽管我意识到(当然)它远非正确:

jQuery("div#normal .m_action").click(function() {
navigator.geolocation.getCurrentPosition(storeAction(this), errorAction).then(function() {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;

jQuery.ajax({
url: "./checkpoint.php",
type: "POST",
data: { action: this.id, user: "driver", key: <?php echo "12345"; ?>, latitude: latitude, longitude: longitude, accuracy: accuracy }
}).done(function(result) {
if(result == "error") {
alert("The action could not be complete. If this persists, please contact dispatch directly.");
} else {
jQuery(action).addClass("m_action_complete");
jQuery(action).removeClass("m_action");
jQuery(action).html(result);
}
}).fail(function(result) {
alert("There was an error, please try again. If this persists, please contact dispatch directly.")
});
});
});

最佳答案

getCurrentPosition() 方法定义为:

navigator.geolocation.getCurrentPosition(success, error, options)

其中 success 是一个回调函数,它将 Position 对象作为其唯一的输入参数。使用该对象您可以获得纬度、经度和精度。参数action可以作为全局变量提供。

关于javascript - HTML5/Javascript 地理位置 : Pass data to callback function -or- suspend async call (with promises)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21671184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com