首页 > 解决方案 > 如何仅在修改变量后执行函数-Javascript和ajax

问题描述

我的 javascript 代码中有两个 ajax 调用。我有一个全局定义的数组'a',它由'success'中的一个ajax调用修改。在第二个 ajax 调用的“成功”中,我想使用更新后的数组“a”以及从第二个 ajax 调用收到的数据。它看起来像这样:

var a = [];
x();
y();


function x(){
    //ajax call 1 - updates the array 'a' in its 'success'. Done async!

}
function y(){
        filters = []   //some filter
        $.ajax({
                type : 'POST',
                url : "get-other-data",
                dataType : 'json',
                async: "true",
                data:JSON.stringify(filters),
                contentType: 'application/json; charset=utf-8',
                success : function(data){

                    while(a.length == 0);
                    z(a,data);           // Want this to execute only after 'a' has been updated


                },
                failure: function(data){
                    alert('got an error');
                }
            });

}
function z(a,data){
  //does something
}

我尝试在第二个 ajax 调用中执行上述操作,但它陷入了无限循环。我已经确认第一个 ajax 调用完美无缺。那么,这是否意味着它创建了全局变量的副本并且即使其他函数进行了更新也不更新它?我需要做哪些改变才能让它发挥作用?

提前非常感谢!

标签: javascriptjqueryajax

解决方案


推荐阅读