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

我有一个 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);
        }
    });
});

#cand div 中我会得到:

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

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

最佳答案

假设您的服务器端脚本没有设置正确的 Content-Type: application/json 响应 header ,您需要使用 dataType: ' 向 jQuery 指示这是 JSON 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
        }));
    });
});

https://stackoverflow.com/questions/8951810/

相关文章:

jquery - 如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC Controll

python - JSON解码错误: Expecting value: line 1 column

json - HTTP 中的 "406-Not Acceptable Response"是什么?

python - 将 JSON 字符串转换为字典未列出

json - 使用jq根据对象中变量的值选择对象

java - 在 Java 中使用 JSON 的 HTTP POST

json - 如何使用 JSON 对象初始化 TypeScript 对象?

python - 让 JSON 对象接受字节或让 urlopen 输出字符串

python - NumPy 数组不是 JSON 可序列化的

javascript - 将带有数字键的 JavaScript 对象转换为数组