【问题标题】:dynamic associative array creation whith jquery and xml使用 jquery 和 xml 创建动态关联数组
【发布时间】:2012-04-04 13:22:16
【问题描述】:

我正在尝试将 xml 文件中的数据存储在关联数组中。 创建数组工作正常,但我无法访问其他函数(即 checkArray())中的数据。

var picSetsData = (function () {
    var _picSets = [];

    $.ajax({
        type: "GET",
        url: "xml/content.xml",
        dataType: "xml",
        success: function (xml) {

            $(xml).find('set').each(function (i) {
                _picSets[i] = [];
                _picSets[i].fehler = [];
                _picSets[i].url = $(this).find('src').text();

                $(this).find('spot').each(function (e) {
                    _picSets[i].fehler[e] = [];
                    _picSets[i].fehler[e].x = $(this).find("x").text();
                    _picSets[i].fehler[e].y = $(this).find("y").text();
                });
            });
        }
    });

    return {
        getPicSets: function () {
            if (_picSets) return _picSets;
            else {
                console.log('error');
            }
        }
    };
})();

checkArray();

function checkArray() {
    console.log(picSetsData.getPicSets().length); // 1
    console.log(picSetsData.getPicSets()); // my Array Data
    console.log(picSetsData.getPicSets()[1]); //undefinded
    console.log(picSetsData.getPicSets()[1].url); //undefinded
}

有什么想法可以解决这个问题吗?谢谢。

【问题讨论】:

    标签: jquery xml arrays associative


    【解决方案1】:

    $.ajax() 调用是异步的,因此周围的函数将在服务器发送数组数据之前很久就返回。

    您可以在“成功”回调执行“checkArray()”工作。

    【讨论】:

    • 您的权利。我把 checkArray() 里面 $(document).ready(function(){...});现在一切正常
    【解决方案2】:

    您已将_picSets 声明为函数picSetsData 内的局部变量。如果你想让它成为一个可以跨函数共享的全局变量,你需要在函数之外声明它。

    【讨论】:

    • 好吧,他正试图从进行 ajax 调用的函数中 return 它,但当然这也行不通。
    【解决方案3】:

    那里没有关联数组,只有常规数组。

    数组索引是从零开始的,所以如果数组中有一项,它的索引为零:

    console.log(picSetsData.getPicSets()[0]);
    

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2012-11-17
      • 2011-07-28
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多