0

我使用 xmlhttprequest 从数据库中获取了这些数据。

[{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}]

我的主要目标是以列形式排列数据,如下所示:

description      location     name   created_at  

方括号让我有点困惑,但它看起来像一个 javascript 数组,但我无法正确解析它。

4

2 回答 2

1

您可以遍历它,并访问每个元素。这是一个将其格式化为一些 HTML 表格的示例。

var data = [{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}];


var results = document.getElementById('results');
htmlString = '<table><tr>';
for( a=0; a<data.length; a++) {
    htmlString = htmlString + '<tr><td>' + data[a]['description'] + '</td><td>' + data[a]['location'] + '</td><td>' + data[a]['name'] + '</td><td>' + data[a]['created_at'] +     '</tr>';

}
htmlString = htmlString + '</table>';
results.innerHTML = htmlString;

在http://jsfiddle.net/R63BJ/有一个 jsfiddle

于 2013-10-04T11:22:58.500 回答
0

就像您使用 XMLHTTRequest 一样,您将在 responesText 中获取数据

 var jsonData=eval('('+responseText+')');

var text="<table><tr><th>description</th><th>location</th>" +
                "<th>name</th><th>created_at</th></tr>";
for(var i=0;i<jsonData.length;i++){


            text+="<td>"+jsonData[i].description+"</td>";
            text+="<td>"+jsonData[i].location+"</td>";
            text+="<td>"+jsonData[i].name+"</td>";
            text+="<td>"+jsonData[i].created_at+"</td>";
            text+="</tr>";

}
text+="</table>"
document.getElementById("tag").innerHTML="";// make sure that data is not Present 
    document.getElementById("tag").innerHTML=text;

并在 Jsp 页面中:

<div id="tag"></tag>
于 2013-10-04T11:23:07.233 回答