如何使用 JavaScript 显示 JSON 数组数据


How to show JSON array data by using javascript?

我有一个ajax返回这样的json数组数据,

[{
    "UserName": "John",
    "Total": "45",
    "Correct(%)": "71.1111",
    "Incorrect(%)": "28.8889"
}, {
    "UserName": "KKK",
    "Total": "42",
    "Correct(%)": "47.6190",
    "Incorrect(%)": "52.3810"
}, {
    "UserName": "AAA",
    "Total": "54",
    "Correct(%)": "81.4815",
    "Incorrect(%)": "18.5185"
}, {
    "UserName": "BBB",
    "Total": "39",
    "Correct(%)": "58.9744",
    "Incorrect(%)": "41.0256"
}]

我想通过使用这样的javascript来显示这些数据,

用户名: 约翰 总计: 45 正确(%): 71.1111
错误(%): 28.8889

用户名: KKK 总计: 42 正确(%): 47.6190
错误(%): 52.3810

用户名: AAA 总计: 54 正确(%): 81.4815
错误(%): 18.5185

用户名: BBB 总计: 39 正确(%): 58.9744
错误(%): 41.0256

所以,我这样尝试,

$.ajax({
                url: 'some.php',
                type: 'post',
                data: {dept:d},
                dataType: 'json',
                success: function(data) {
                    console.log("success");
                    var temp = "";
                    if(data && data!="") {
                        for(var i=0; i<data.length; i++) {
                            $.each(data,function(k,v){
                                $.each(v,function(k,s){
                                    temp +=k+': <b>'+s+'</b> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
                                });
                                temp +="<br/><br/>";
                                console.log(temp);
                            });
                        }
                        document.getElementById('user').innerHTML= temp;
                    }
});

但是,我为每个用户提供了五行。循环时我错了。那么,我该怎么做呢?

尝试删除for循环。

 //for(var i=0; i<data.length; i++) {
    $.each(data,function(k,v){
        $.each(v,function(k,s){
           temp +=k+': <b>'+s+'</b> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
        });
        temp +="<br/><br/>";
        console.log(temp);
    });
 //}

使用以下代码:

$.ajax({
    url: 'some.php',
    type: 'post',
    data: {dept:d},
    dataType: 'json',
    success: function(data) {
        console.log("success");
        var temp = '';
        if(data && data != "") {
            var temp = '<ul>';
            for(var i = 0; i < data.length; i++) {
                temp += '<li>UserName: ' + data[i]['UserName'] + '&nbsp;Total: ' + data[i]['Total'] + '&nbsp;Correct(%): ' + data[i]['Correct(%)'] + '&nbsp;Incorrect(%): ' + data[i]['Incorrect(%)'] + '</li>';
            }
            temp += '</ul>';
            document.getElementById('user').innerHTML = temp;
        }
    }
});

你只需要使用 1 $.each 循环,否则你正在循环遍历所有数据多次时间。