Iterating through JSON within a $.ajax success

后端 未结 2 1852
谎友^
谎友^ 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:19

    You need to add:

    dataType: 'json',
    

    .. so you should have:

    $("#button").click(function(){
    
    $.ajax({
        url: 'http://localhost/test.php',
        type: 'get',
        dataType: 'json',
        success: function(data) {  
         $.each(data.COLUMNS, function(item) {
            console.log(item);
            });
        },
        error: function(e) {
            console.log(e.message);
        }
    });
    
    });
    

    .. as well as ensuring that you are referencing COLUMNS in the each statement.

    getJson is also another way of doing it..

    http://api.jquery.com/jQuery.getJSON/

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题