-->

Callback Firing Too Early when External File Acces

2019-09-19 06:18发布

问题:

I am trying to parse a simple XML file,

<gallery>
    <photo><file>Image1</file></photo>
    <photo><file>Image2</file></photo>
    <photo><file>Image3</file></photo>
<gallery>

then execute a callback function. The parsing works fine, but I cannot get the callback to fire after the parse. I am trying to obtain

Image1
Image2
Image3
Done!

but Done! is always being output before the images can be listed. Why is this? Here is my Jquery code:

$(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>');
});
});

Is a delay timer necessary or are there ways to use .done, .resolve, and so forth?

回答1:

this should work, also take a look at the resolve() function.

$(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();

});

best

M



标签: xml callback