jQuery loop over JSON result from AJAX Success?

2019-01-01 14:21发布

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});

标签: jquery ajax json
10条回答
大哥的爱人
2楼-- · 2019-01-01 15:04

if you don't want alert, that is u want html, then do this

...
    $.each(data, function(index) {
        $("#pr_result").append(data[index].dbcolumn);
    });
...

NOTE: use "append" not "html" else the last result is what you will be seeing on your html view

then your html code should look like this

...
<div id="pr_result"></div>
...

You can also style (add class) the div in the jquery before it renders as html

查看更多
孤独寂梦人
3楼-- · 2019-01-01 15:08

Access the json array like you would any other array.

for(var i =0;i < itemData.length-1;i++)
{
  var item = itemData[i];
  alert(item.Test1 + item.Test2 + item.Test3);
}
查看更多
弹指情弦暗扣
4楼-- · 2019-01-01 15:09

For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.

You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.

jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    data: data, 
    dataType: 'json', // ** ensure you add this line **
    success: function(data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
        });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});
查看更多
泛滥B
5楼-- · 2019-01-01 15:13

$each will work.. Another option is jQuery Ajax Callback for array result

function displayResultForLog(result) 
{
       if (result.hasOwnProperty("d")) {
           result = result.d
       }

    if (result !== undefined && result != null )
    {
        if (result.hasOwnProperty('length')) 
        {
            if (result.length >= 1) 
            {
                for (i = 0; i < result.length; i++) {

                    var sentDate = result[i];

                }
            }
            else 
            {
                $(requiredTable).append('Length is 0');
            }
        }

        else 
        {
            $(requiredTable).append('Length is not available.');
        }

    }
    else 
    {
        $(requiredTable).append('Result is null.');
    }
  }
查看更多
登录 后发表回答