Javascript局部变量未更新
我编写了这个函数来检测和更新postLat和postLon变量Javascript局部变量未更新,javascript,geolocation,local-variables,Javascript,Geolocation,Local Variables,我编写了这个函数来检测和更新postLat和postLon变量 function searchAddSubmit(){ var shopId = 1; //random number to test the function var postLon, postLat; var shopTime = $("#selected-search-result-minutes").val(); navigator.geolocation.getCurrentPosition
function searchAddSubmit(){
var shopId = 1; //random number to test the function
var postLon, postLat;
var shopTime = $("#selected-search-result-minutes").val();
navigator.geolocation.getCurrentPosition(function(position){
postLat=position.coords.latitude;
postLon=position.coords.longitude;
console.log(postLat);
console.log(postLon);
console.log('reun');
},function(error){});
console.log(postLat+" 1231");
console.log(postLon+" 1231");
$.ajax({
type: "POST",
url: "search-add-process.php",
cache: false,
dataType: "json",
data:{
id: shopId,
time: shopTime, //this value is taken from a form input
lat: postLat,
lon: postLon
},
success: function (data) {
if(data.error === true) {
alert(data.msg);
} else {
alert(data.msg);
//remove output when successful
}
}
});
}
我使用Chrome的Javascript控制台工具来检查变量(如使用Console.log()
打印的),结果如下:
undefined 1231
undefined 1235
1.2957797
103.8501069
ruen
说到这里,我有以下问题:
postLon
和postLat
没有更新?事实上,未定义的变量传递给ajax块中的search add process.php
,而不是实际值navigator.geolocation.getCurrentPosition()
函数在console.log(postLat+“1231”)
行之后运行?如果我错了,请纠正我,我总是假设Javascript会逐行执行您首先告诉GeolocationAPI尝试查找用户的当前位置,然后在您完成其余工作时让它去搜索。这称为异步执行。换句话说,您让地理定位API花时间搜索并找到用户的位置,同时完成其余的工作(剩下的代码正在执行)。然后,当API找到位置时,它会执行您传递给它的函数
将ajax的代码放入成功回调中,一切都会好起来。将整个
$.ajax({…})
在getCurrentPosition
回调函数中调用;
e、 g.将其直接放在行
console.log('reun')之前或之后代码>是一个AJAX调用吗?您提供给它的回调函数可能在调用console.log()
之后运行。@Blender,getCurrentPosition()
属于Geolocation API,在HTML5中是新的。@Blender,您可以在以下位置查看Geolocation API:这将启动一个异步请求来检测用户的位置。这也是异步的,所以同样的问题也存在。但是如果无法检索latlon,ajax代码不会运行吗postLat
和postLon
用于在用户输入店铺时间时跟踪用户的位置(用于跟踪兼职人员在地面漫游时的位置)。