全局变量未在 jQuery 中设置


$(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值为空,即使我在 ajax 返回中获得一些值我希望将我的bwr_w设置为全局变量,以便当我从 ajax 获得一些结果时,它应该更改我的地图引脚。

问题是因为$.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 }
        });
    });
});

看这里

$(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()
        }
      });
    }); 
});

相关内容

  • 没有找到相关文章

最新更新