全局变量不会在AJAX成功内从函数更新 [英] global variable won't update from function within AJAX success
问题描述
好的,所以我似乎无法在通过ajax后更改systemPath的全局变量,它可以在ajax内运行,但是我需要ajax之外的更新后的变量.基本上,我试图从xml创建路径数组,并使用它们查找其他可以从中生成表的xml文件.
OK, so I cannot seem to be able to change the global variable of systemPath after it goes through the ajax.It will work inside of ajax, but I need that updated variable outside of ajax. basically I'm trying to create an array of paths from xml and use them to locate other xml files that I can generate a table from.
有人知道这是怎么回事吗? ajax是否在变量设置之前运行,这就是为什么ajax之后的数组长度为0的原因?
Does anyone know what's going on here? Does ajax run before the variable is set and that is why I get an array length of 0 after the ajax?
var systemPath = new Array();
var techDigestArr = new Array();
var addToArray = function(thisarray, toPush){
thisarray.push(toPush);
}
$.ajax({
url: fullPath+"technical/systems/systems.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data){
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
$(xml).find("system").each(function(){
var urlString = fullPath + "technical/system_" + $(this).attr("id") + "/" + $(this).attr("id") + "tech-digest.xml <br />";
//alert(urlString);
$("#td-articles").append(systemPath.length + urlString);
addToArray(systemPath,urlString);
//systemPath.push(urlString);
});
$("#msg-output").append("total - " +systemPath.length);//Returns 48
},//END SUCCSESS
error: function(){
alert("Sorry - ");
history.go(-1);
}
});//END AJAX CALL
$(document).ready(function(){
//$("#msg-output").append("total - " + systemPath.length); Returns 0
});
推荐答案
ajax是异步运行的.事情在您的代码中按此顺序执行.
The ajax is ran asynchronously. Things execute in this order in your code.
-
$.ajax()
之前的内容
-
$.ajax()
启动ajax调用(在等待响应的同时,它继续运行其余代码) -
success
回调
$.ajax()
之后的内容
- stuff before
$.ajax()
$.ajax()
initiates an ajax call (while waiting for the response it continues to run the rest of the code)- stuff after
$.ajax()
success
callback
请注意,取决于通话3和4的速度,通话的顺序可能相反(此处不是这种情况)
Note that depending on how fast the call is 3 and 4 might occur in reverse order (not the case here)
因此,当执行$(document).ready()
时,ajax调用可能尚未返回,因此成功回调中的代码没有机会执行.如果您很幸运并且连接速度很快,那么响应可能会在文档准备好之前就出现了,但这不太可能.
So when $(document).ready()
is executed the ajax call might not have returned yet, so the code in the success callback didn't have a chance to execute. If you are lucky and have a fast connection than maybe the response will come before document ready, but it's unlikely.
只要您可以看到全局变量已更新,就可以设置超时时间:
Just so you can see that the global variable gets updated you can set a timeout:
$(document).ready(function(){
setTimeout(function(){
$("#msg-output").append("total - " + systemPath.length);
//if the delay set below is more than the time between the ajax request and the server response than this will print the correct value
},2000);
});
这篇关于全局变量不会在AJAX成功内从函数更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!