xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<menulist>
    <menu>
        <name>Home</name>
        <url>index.html</url>
    </menu>
    <menu>
        <name>Graphic</name>
        <url>graphic.html</url>
    </menu>
</menulist>jQuery代码:
function xmlReader(file) {
var nodes = new Array();
$.get(file, function(xml) {
$($(xml).children().get(0)).children().each(function() {
var node = new Object();
$(this).children().each(function() {
eval("node." + $(this).get(0).tagName + " = '" + $(this).get(0).text + "'");
});
nodes.push(node);
});
});
return nodes;
}

我想用jQuery读取xml文件,将一级结点存在数组中用于其他操作,保存的格式是:
nodes[0].name = 'Home', nodes[0].url = 'index.html'
nodes[1].name = 'Graphic', nodes[1].url = 'graphic.html'
在调试中可以看到nodes.push(node)将值已经存进去了,但是在return nodes的时候nodes为空,请问各位高手这是怎么回事,怎么解决这个问题。

解决方案 »

  1.   

    因为ajax是异步的,还没执行到回调就已经return nodes了,用$.ajax并且配置为同步的    function xmlReader(file) {
            var nodes = new Array();
            $.ajax({
                url: file
             , async: false/////
             , success: function (xml) {
                 $($(xml).children().get(0)).children().each(function () {
                     var node = new Object();
                     $(this).children().each(function () {
                         eval("node." + $(this).get(0).tagName + " = '" + $(this).get(0).text + "'");
                     });
                     nodes.push(node);
                 });
              }
            });        /*$.get(file, function (xml) {
                $($(xml).children().get(0)).children().each(function () {
                    var node = new Object();
                    $(this).children().each(function () {
                        eval("node." + $(this).get(0).tagName + " = '" + $(this).get(0).text + "'");
                    });
                    nodes.push(node);
                });
            });*/
            return nodes;
        }