javascript - 如何仅在修改变量后执行函数-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 调用完美无缺。那么,这是否意味着它创建了全局变量的副本并且即使其他函数进行了更新也不更新它?我需要做哪些改变才能让它发挥作用?
提前非常感谢!
解决方案
推荐阅读
- excel - 在一行中查找一个单元格并复制值
- python - 如何在 sci-kit learn 中使用 GP.fit 进行多维输入?
- java - 将字符串数组转换为 JSONArray
- javascript - 如何在javascript中创建自己的调用函数?
- laravel - 无需用户登录的简单身份验证
- clojure - 如何在 Compojure 中使用 CORS 和 JSON 响应?
- php - 搜索一个值并获取其他值
- python - Pipreqs:UnicodeDecodeError:'charmap'编解码器无法解码位置 1206 中的字节 0x98:字符映射到
- c# - 以良好的性能可靠地监视大量客户端的最佳方法是什么
- python - 如何将for循环打印为函数中的最后一件事?