利用原生ajax调接口创建表格,渲染页面的代码实现教程
程序员文章站
2023-10-31 09:13:10
效果
php 代码
效果
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> <p id="container"></p> <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> <!--