Iterating through JSON within a $.ajax success

后端 未结 2 1893
谎友^
谎友^ 2021-01-17 17:38

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 t

2条回答
  •  忘掉有多难
    2021-01-17 18:35

    Assuming your JSON is like this

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

    You can query it like this

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

    Sample : http://jsfiddle.net/4HxSr/9/

    EDIT : As per the JSON OP Posted later

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

    As per your JSON like this

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

    You should query it like this

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

    Working sample : http://jsfiddle.net/4HxSr/19/

提交回复
热议问题