Xml 访问外部文件时,回调过早触发

Xml 访问外部文件时,回调过早触发,xml,callback,Xml,Callback,我试图解析一个简单的XML文件 <gallery> <photo><file>Image1</file></photo> <photo><file>Image2</file></photo> <photo><file>Image3</file></photo> <gallery> 但是完成了!总是在可以列

我试图解析一个简单的XML文件

<gallery>
    <photo><file>Image1</file></photo>
    <photo><file>Image2</file></photo>
    <photo><file>Image3</file></photo>
<gallery>
但是完成了!总是在可以列出图像之前输出。为什么会这样?以下是我的Jquery代码:

$(document).ready(function(){ 
    var imgArray=[];

    function xmlparse(callback){
    $.get("gallery.xml",{},function(xml){
    $('photo',xml).each(function(i){
        file = $(this).find("file").text();
        (imgArray).push(file);
            $('.content').append(imgArray[i] + '<br>'); 
        i++;
    });
    });
    if(typeof callback == "function") callback();
    };

    xmlparse(function(){
    $('.content').append('Done! <br>');
});
});
$(文档).ready(函数(){
var Imgaray=[];
函数xmlparse(回调){
$.get(“gallery.xml”,{},函数(xml){
$('photo',xml)。每个(函数(i){
file=$(this.find(“file”).text();
推送(文件);
$('.content').append(imgArray[i]+'
'); i++; }); }); if(typeof callback==“function”)callback(); }; xmlparse(函数(){ $(“.content').append('Done!
); }); });

是否需要延迟计时器,或者是否有使用.done、.resolve等的方法?

这应该可以工作,还可以查看resolve()函数

$(document).ready(function(){ 

var imgArray=[];
function xmlparse(){
$.get("gallery.xml",{},function(xml){
     $('photo',xml).each(function(i){
        file = $(this).find("file").text();
         (imgArray).push(file);
         $('.content').append(imgArray[i] + '<br>'); 
         i++;
     }).promise().done( function(){ 
            $('.content').append('Done! <br>'); });
     });

xmlparse();

});
$(文档).ready(函数(){
var Imgaray=[];
函数xmlparse(){
$.get(“gallery.xml”,{},函数(xml){
$('photo',xml)。每个(函数(i){
file=$(this.find(“file”).text();
推送(文件);
$('.content').append(imgArray[i]+'
'); i++; }).promise().done(函数(){ $('.content').append('Done!
');}); }); xmlparse(); });
最好的


M

Mboeckle,你真是个怪人。我那本很棒的jQuery书没有这么先进,我想。承诺只是为了动画。多谢!尽管我还是很好奇……如果xmlparse()我的回调函数不是解析器,而是一个内部函数。是因为访问另一个文件的延迟吗?是的,请接受答案-您通过$get加载文件,然后附加。向$each循环承诺;尝试向$get添加.done应该工作到或.complete(如果未成功,但已完成)您可以在其中添加每个循环
$(document).ready(function(){ 

var imgArray=[];
function xmlparse(){
$.get("gallery.xml",{},function(xml){
     $('photo',xml).each(function(i){
        file = $(this).find("file").text();
         (imgArray).push(file);
         $('.content').append(imgArray[i] + '<br>'); 
         i++;
     }).promise().done( function(){ 
            $('.content').append('Done! <br>'); });
     });

xmlparse();

});