2009-09-27 104 views
6

我正在使用jQuery來解析XML文件,並且我試圖使用jQuery .each循環將XML文件中的每個元素推送到一個數組。奇怪的是,如果我警告循環中數組的值,它應該出來,但如果在循環結束後嘗試提醒數組中的值,則會導致「未定義」。推送到jQuery每個循環內的數組

當你在這種類型的循環中將值推入數組時,會發生什麼奇怪的事情嗎?


這裏是JavaScript:

var splashArray = new Array(); 

// Load the Splash XML file and assign each image within to an array 
$.get('splash.xml', function(xml) { 
    $('image', xml).each(function (i) { 
     splashArray.push($(this).attr("src")); 
    }); 
}); 

alert(splashArray[1]); // Results in undefined 



這裏是XML:

<?xml version="1.0" encoding="UTF-8"?> 
<site>  
    <image src="splash1.jpg" /> 
    <image src="splash2.jpg" /> 
    <image src="splash3.jpg" /> 
    <image src="splash4.jpg" /> 
    <image src="splash5.jpg" /> 
    <image src="splash6.png" /> 
</site> 

回答

10

正確的變體:

var splashArray = new Array(); 

// Load the Splash XML file and assign each image within to an array 
$.get('splash.xml', function(xml) { 
     $('image', xml).each(function (i) { 
       splashArray.push($(this).attr("src")); 
     }); 
     alert(splashArray[1]); 
}); 

在您的代碼警報(splashArray [1])的變體中;在ajax獲取xml結果之前執行,因此splashArray爲空,當您嘗試使用索引1提醒元素時。當線程等待服務器響應時,您的代碼僅適用於同步模式。在異步模式下,您應該使用回調函數。

變體與回調:

var splashArray = new Array(); 

// Load the Splash XML file and assign each image within to an array 
$.get('splash.xml', function(xml) { 
     $('image', xml).each(function (i) { 
       splashArray.push($(this).attr("src")); 
     }); 
     work_with_splash(); 
}); 

function work_with_splash() { 
    alert(splashArray[1]); 
} 

或一個或多個圖案(僞代碼):

function process(ajax_is_done) { 
    if (!ajax_is_done) { 
     ajax(function (result) { 
      import_result(result); 
      process(true); 
     }) 
    } 
} 
process(); 
+0

仍然在這裏未定義結果.. – jakeisonline 2009-09-27 20:07:59

+0

對我來說它提醒splash2.jpg – Anatoliy 2009-09-27 20:12:17

+0

是的,你的代碼將正確地檢索$ .get塊內的數組,但爲什麼它不會在$ .get之外檢索它塊。也許我不清楚。我的問題是沒有讓alert()工作,它使得數組值可以在後面的代碼中檢索。 – cmal 2009-09-27 20:14:12

2

正在填充陣列之前被您可以提醒。您需要了解XHR/Ajax是異步的(而不是同步的),所以警報不會在回調函數後運行總是,因爲執行實際的HTTP請求需要幾秒鐘才能獲取xml,回調可確保在XHR內容完成後填充它。

作品:

var splashArray = []; 

function fn() { 
    alert(splashArray[1]); 
} 

$.get('splash.xml', function(xml) { 
     $('image', xml).each(function (i) { 
       splashArray.push($(this).attr("src")); 
     }); 
     fn(); 
}); 

不起作用:

var splashArray = []; 

$.get('splash.xml', function(xml) { 
     $('image', xml).each(function (i) { 
       splashArray.push($(this).attr("src")); 
     }); 
     // this will populate the array almost always AFTER the alert below. 
}); 


alert(splashArray[1]); // this will almost ALWAYS alert BEFORE the callback function is done 
+0

實際上這兩種方法似乎都很好,所以dataType位並不重要。你確定這是正確的XML文件路徑嗎?也許你需要一個根相對的,如'/xml/splash.xml'?試試Firebug net標籤,看看你是否在請求正確的URI。 – 2009-09-27 20:15:06

+0

這幾乎可以工作,但你仍然無法調用splashArray以外的東西。ajax函數,它導致未定義。 – jakeisonline 2009-09-27 20:16:23

+0

我以爲你在「在解決方案上工作」?而且我沒有在回調之外發出警報,我在回調中提醒它,因此它可以工作,並且我已經測試過它。 – 2009-09-27 20:18:19

0

如果你不想使用標準的回調,另一種則是觸發jQuery的事件。