2009-09-27 54 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的事件。