$(function(){
var bwr_w = null; //global variable
//below function gets the dynamic data
function myfunc() {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year="+val ,
cache: false,
success: function(result){
bwr_w= result.replace(/\s+/g, ''); //want to set the data again
}
});
}
myfunc(); //my dynamic function gets called
$(".container_map").mapael({
map : {
name : "usa_states"
},
plots: {
bwr_w //this should work as per myfunc()
}
});
});--我总是将bwr_w值作为null,即使在ajax返回中得到某个值,我也希望将bwr_w设置为全局变量,以便当我从ajax获得一些结果时,它应该更改我的映射引脚。
发布于 2015-02-15 21:58:47
问题在于$.ajax调用是异步的。这意味着在AJAX调用返回数据之前就退出了myfunc。要解决此问题,请将所有依赖于回调中返回的数据的代码:
$(function () {
var bwr_w = null; //global variable
//below function gets the dynamic data
function myfunc() {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year=" + val,
cache: false,
success: function (result) {
bwr_w = result.replace(/\s+/g, ''); //want to set the data again
$(".container_map").mapael({
map: { name: "usa_states" },
plots: { bwr }
});
}
});
}
myfunc();
});如果希望在每次调用myfunc时执行不同的逻辑,则将其作为回调函数传入:
$(function () {
//below function gets the dynamic data
function myfunc(callback) {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year=" + val,
cache: false,
success: function (result) {
var bwr_w = result.replace(/\s+/g, ''); //want to set the data again
callback(bwr_w);
}
});
}
myfunc(function (bwr) {
$(".container_map").mapael({
map: { name: "usa_states" },
plots: { bwr }
});
});
});发布于 2015-02-15 21:59:46
看这里
$(function(){
var bwr_w = null; //global variable
//below function gets the dynamic data
function myfunc(then) {
var val = '2011'
$.ajax({
type: "POST",
url: "allmaps.php",
data: "year="+val ,
cache: false,
success: function(result){
then && then(result);
}
});
}
myfunc(function() {
bwr_w= result.replace(/\s+/g, ''); //want to set the data again
$(".container_map").mapael({
map : {
name : "usa_states"
},
plots: {
bwr_w //this should work as per myfunc()
}
});
});
});https://stackoverflow.com/questions/28531629
复制相似问题