如何使用javascript显示JSON数组数据?

时间:2016-02-08 03:33:20

标签: javascript php json

我有一个像这样的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;
                    }
});

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

3 个答案:

答案 0 :(得分:1)

尝试删除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);
    });
 //}

答案 1 :(得分:1)

使用此代码:

$.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;
        }
    }
});

答案 2 :(得分:0)

你只需要使用1 $ .each循环,否则你会循环遍历所有数据。