小编典典

如何使用jQuery / JavaScript解析JSON数据?

ajax

我有一个AJAX调用,返回的是这样的JSON:

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
            var names = data
            $('#cand').html(data);
        }
    });
});

#canddiv中,我将得到:

[ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ]

如何遍历此数据并将每个名称放在div中?


阅读 286

收藏
2020-07-26

共1个答案

小编典典

假设您的服务器端脚本未设置正确的Content-Type: application/json响应标头,则需要使用dataType: 'json'参数向jQuery指示这是JSON 。

然后,您可以使用该$.each()函数遍历数据:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

或使用$.getJSON方法:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});
2020-07-26