[英]global variable won't update from function within AJAX success
好的,所以我似乎無法在通過ajax后更改systemPath的全局變量,它可以在ajax內部運行,但是我需要在ajax外部進行更新的變量。 基本上,我正在嘗試從xml創建路徑數組,並使用它們查找其他可以生成表的xml文件。
有人知道這是怎么回事嗎? ajax是否在變量設置之前運行,這就是為什么ajax之后的數組長度為0的原因?
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是異步運行的。 事情在您的代碼中按此順序執行。
$.ajax()
之前的內容 $.ajax()
啟動一個ajax調用(在等待響應的同時,它繼續運行其余代碼) $.ajax()
success
回調 請注意,取決於通話速度有多快,通話3和4的順序可能相反(此處不是這種情況)
因此,當執行$(document).ready()
,ajax調用可能尚未返回,因此成功回調中的代碼沒有機會執行。 如果您很幸運並且連接速度很快,那么響應可能會在文檔准備好之前出現,但這不太可能。
就像這樣,您可以看到全局變量被更新了,您可以設置一個超時:
$(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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.