jquery 中未设置全局变量

global variable is not set in 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()
        }
    });

});

即使我在 ajax return 中得到一些值,我总是得到 bwr_w 值作为 null 我希望我的 bwr_w 被设置为全局变量,这样当我从 ajax 得到一些结果时它应该改变我的地图引脚。

问题是因为 $.ajax 调用是异步的。这意味着您的 myfunc 在 数据从 AJAX 调用返回之前 退出。要解决此问题,请将所有依赖于返回数据的代码放在回调中:

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