相关疑难解决方法(0)

jQuery解析JSON多维数组

我有一个像这样的JSON数组:

{
  "forum":[
    {
      "id":"1",
      "created":"2010-03-19 ",
      "updated":"2010-03-19 ","user_id":"1",
      "vanity":"gamers",
      "displayname":"gamers",
      "private":"0",
      "description":"All things gaming",
      "count_followers":"62",
      "count_members":"0",
      "count_messages":"5",
      "count_badges":"0",
      "top_badges":"",
      "category_id":"5",
      "logo":"gamers.jpeg",
      "theme_id":"1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想使用jQuery .getJSON来返回每个数组值的值,但我不确定如何访问它们.

到目前为止,我有这个jQuery代码:

$.get('forums.php', function(json, textStatus) {
            //optional stuff to do after success
            alert(textStatus);
            alert(json);

        });
Run Code Online (Sandbox Code Playgroud)

我怎么能用jQuery做到这一点?

arrays jquery json

21
推荐指数
1
解决办法
9万
查看次数

多维数组和jQuery的getJSON

我向我的应用程序中的控制器提交了一个getJSON请求,该控制器返回带有2个"应用程序"的有效JSON.我知道这个事实就好像我将alert语句移动到jQuery的每个函数中它会给我预期的结果.

我试图将这些数据存储在一个多维数组中,以便以后与extJS'菜单控件一起使用.

码:

Ext.onReady(function() {
    var applicationList = [];
    jQuery.getJSON('index.php/applications', function(data) {
        jQuery.each(data.applications, function (i, app) {
            applicationList[i] = [];
            applicationList[i]['text'] = app['title'];
            applicationList[i]['id'] = app['slug'];
        });
    });
    alert(applicationList[0]['text']);

    var applicationMenu = Ext.menu.Menu({
        items: applicationList
    });
});
Run Code Online (Sandbox Code Playgroud)

JSON响应:

{"applications":[{"slug":"test","title":"Test"},{"slug":"hardware","title":"Hardware"}]}
Run Code Online (Sandbox Code Playgroud)

预期结果:

测试

实际结果(来自Firebug):

applicationList [0]未定义

如果我用alert()以下代码替换上面的代码,我会得到一个带有"remove"文本的警告窗口:

for (p in applicationList) {
    alert(p);
}
Run Code Online (Sandbox Code Playgroud)

现在,我的想法是JSON请求没有及时完成,alert()因此我将使用命名回调函数来确保请求已完成:

var data;
jQuery.getJSON('index.php/applications', get_applications(data));

function get_applications(data) {
    jQuery.each(data.applications, function (i, app) {
        applicationList[i] = [];
        applicationList[i]['text'] = app['title'];
        applicationList[i]['id'] = app['slug'];
    });
}; …
Run Code Online (Sandbox Code Playgroud)

javascript jquery json

2
推荐指数
1
解决办法
3万
查看次数

标签 统计

jquery ×2

json ×2

arrays ×1

javascript ×1