开发者

Using Javascript / JQuery to access an array built from an external XML file

I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first pi开发者_C百科ece of advice on here.

I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.

So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?

Here is my code... Please help!!

$.ajax({
    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: do_xmlParser
});

function do_xmlParser(xml)
{
    var myArray = new Array();

    $(xml).find("tag").each(function ()
    {
        myArray.push($(this).find("innerTag").text());
    });

    console.log("inside "+myArray); // This outputs the array I am expecting

    return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"


You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.

The way you have it now, the actual execution of code will go:

ajax -> file being requested -> console.log -> 
        file transfer done -> success handler

If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:

var myArray = [],
do_xmlParser = function (xml)
{
    $(xml).find("tag").each(function ()
    {
        myArray.push($(this).find("innerTag").text());
    });
};

$.ajax({
    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: do_xmlParser,
    async: false
});

console.log("outside: " + myArray);

The async option doesn't work for cross-domain requests, though.

NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.

Edit:

Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).


look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.

console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜