在$ .ajax成功中通过JSON迭代 [英] Iterating through JSON within a $.ajax success

查看:72
本文介绍了在$ .ajax成功中通过JSON迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击按钮时,我想返回一些数据并遍历JSON,以便我可以将结果附加到表格行。

When a user clicks a button I want to return some data and iterate through the JSON so that I can append the results to a table row.

此时我只是想让我的循环工作,这是我的代码。

At this point I am just trying to get my loop to work, here's my code.

我的JSON回来如下:{COLUMNS:[username,password ],DATA:[[foo,bar]]}

My JSON is coming back as follows: {"COLUMNS":["username","password"],"DATA":[["foo", "bar"]]}

$("#button").click(function(){

    $.ajax({
        url: 'http://localhost/test.php',
        type: 'get',
        success: function(data) {  
         $.each(data.items, function(item) {
            console.log(item);
            });
        },
        error: function(e) {
            console.log(e.message);
        }
    });

});

我收到一个jQuery(第16行,a未定义)错误。我做错了什么?

I'm getting a jQuery (line 16, a is not defined) error. What am I doing wrong?

推荐答案

假设您的 JSON 是这样的

var item=  {
        "items": [
                  { "FirstName":"John" , "LastName":"Doe" },
                  { "FirstName":"Anna" , "LastName":"Smith" },
                  { "FirstName":"Peter" , "LastName":"Jones" }
                 ]
           }

你可以像这样查询

$.each(item.items, function(index,item) {        
    alert(item.FirstName+" "+item.LastName)
});

示例: http://jsfiddle.net/4HxSr/9/

编辑:根据JSON OP稍后发布

您的 JSON 没有物品,因此无效。

Your JSON does not have an items, so it is invalid.

根据你的JSON这样

var item= {  "COLUMNS": [  "username", "password" ],
             "DATA": [    [ "foo", "bar"  ] ,[ "foo2", "bar2"  ]]
          }

您应该像这样查询

console.debug(item.COLUMNS[0])
console.debug(item.COLUMNS[1])

 $.each(item.DATA, function(index,item) {        
    console.debug(item[0])
    console.debug(item[1])
  });

工作样本: http://jsfiddle.net/4HxSr/19/

这篇关于在$ .ajax成功中通过JSON迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆