效果
php 代码
<?php
header( "Content-Type: application/json" );
$keys = explode( ",", "num,name,gender,birthdate,join_date,address,email,phone" );
if ( $_SERVER[ "REQUEST_METHOD" ] == "GET" ) {
$dataStr = file_get_contents( "./db.csv" );
$list = explode( "\r\n", $dataStr );
$datas = array();
foreach( $list as $row ) {
$tmp = explode( ",", $row );
$datas[] = array_combine( $keys, $tmp );
}
echo json_encode(array(
"success"=> true,
"result"=> $datas
));
exit;
}
echo json_encode(array(
"success"=> false
));
?>
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>列表显示</title>
</head>
<body>
<div id="container"></div>
<script>
// 请求获得数据
var xhr = new XMLHttpRequest();
xhr.open("GET", "./list.php");
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
if (data.success) {
// 生成 table
var table = document.createElement("table"),
thead = document.createElement("thead"),
tbody = document.createElement("tbody");
table.border = 1;
table.width = 1000;
table.appendChild(thead);
table.appendChild(tbody);
// 生成表头
// thead.innerHTML = Object.keys(data.result[0]).map(function (v) {
// return "<th>" + v + "</th>";
// }).join("");
var theadHtml = ''
for (var k in data.result[0]) {
theadHtml += "<th>" + k + "</th>"
}
thead.innerHTML = theadHtml
// 生成数据
data.result.forEach(function (row) {
var tr = document.createElement("tr");
// 这个方法也可以
// Object.values(row).forEach(function (tdata) {
// var td = document.createElement("td");
// td.innerHTML = tdata;
// tr.appendChild(td);
// });
for (var k in row) {
var td = document.createElement("td");
td.innerHTML = row[k];
tr.appendChild(td);
}
tbody.appendChild(tr);
});
// 将 table 加到页面中
document.getElementById("container").appendChild(table);
}
};
xhr.send();
</script>
</body>
</html>
<!--