如何使用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响应头,您需要使用dataType:’json’参数向jQuery指示这是JSON。

然后你可以使用$.each()函数循环遍历数据:

$.ajax({ 
    type: 'GET',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,element) {
        $('body').append($('<div>',{
            text: element.name
        }));
    });
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...