如何在函数外部使用函数中的变量。console.log(response)显示内容是从php获取的。警报(Lng)显示为undefined。为什么?这个脚本有什么问题,我已经写了一段时间了。
下面是脚本。
var lat;
var lng ;
$.ajax({
type: 'GET',
url: 'getlocation.php',
data: 'param=no' ,
dataType: 'JSON',
success: function (response) {
console.log(response);
lat = response.latitude;
lng = response.latitude;
},
error: function (response){
alert (response);
}
});
alert( lng);发布于 2015-07-24 00:06:04
因为当代码运行到alert(lng)行时,没有设置变量lng。
Ajax调用是异步的。这意味着,JS引擎进入了流程:
$.ajax...)(此时,由于网络运行较慢,因此JS引擎选择继续执行以下行。它在响应完成后返回。)
alert(lng)行。此时,仍然是undefined.function(response)...。回调函数中的警报会得到你想要的。https://stackoverflow.com/questions/31592590
复制相似问题