在ajax回调中使用googlemap变量
为什么在ajax回调函数(success)中无法访问map变量,而其他变量则无法访问 为了进一步解释我的问题,我在下面的代码中添加了注释在ajax回调中使用googlemap变量,ajax,google-maps,Ajax,Google Maps,为什么在ajax回调函数(success)中无法访问map变量,而其他变量则无法访问 为了进一步解释我的问题,我在下面的代码中添加了注释 var map; var g = 10; function initialize() { var mapOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644) }; map = new google.maps.Map(do
var map;
var g = 10;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map_el'), mapOptions);
g = 15;
alert(g); // Gives 15
alert(map.getCenter()); // Gives correct values
}
但在下面的函数中ajax回调请求。我面临着有线的回应
$(document).ready(function ()
{
initialize();
$.ajax({
url: 'ajax.aspx/getLocation',
type: "POST",
contentType: "application/json; charset=uft-8",
dataType: 'json',
success: function (data)
{
alert(g); // Gives 15
alert(map.getCenter()); // Gives error => map is undefined
}
});
});
注意:上述两个函数在脚本标记中位于同一范围内您的
初始化
函数似乎正在异步执行。因此,请尝试使用类似的setTimeout()
来进行ajax调用,并留出一点时间延迟
$(document).ready(function () {
initialize();
setTimeout(function () {
$.ajax({
url: 'ajax.aspx/getLocation',
type: "POST",
contentType: "application/json; charset=uft-8",
dataType: 'json',
success: function (data)
{
alert(g); // Gives 15
alert(map.getCenter()); // Gives error => map is undefined
}
});
}, 10);
});
或者使用回调
进行确认。。错误是地图未定义?是。这就是错误所在。