基于HTML+CSS+JavaScript+jQuery+Ajax+JSON的读取json格式txt文本文件
HTML文件内容
<!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">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<title>Title</title>
</head>
<style>
table{
text-align: center;
}
#btn{
width: 70px;
color: palevioletred;
background-color: darkseagreen;
}
td{
width: 150px;
background-color: aquamarine;
}
</style>
<body>
<!--数据采用data.txt-->
<center>
<input type="button" id="btn" value="查询数据">
<table bgcolor="aqua" border="1" id="table1">
<tr>
<th>学校</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</table>
</center>
</body>
<script charset="UTF-8">
$("#btn").click(function () {
$.ajax({
type:"get",//请求方式
url:"txt/data.txt",//请求地址
data:{//请求数据,json对象
//"age":"19"
},
dataType:"json",//json格式
//请求成功调用
success:function (data) {//data是形参名,代表返回数据
//console.log(data);
// var object=JSON.parse(data);
// console.log(object);
//遍历数组
for(var i=0;i<data.length;i++)
{var ul=$("<tr></tr>");
var user=data[i];
var li="<td>"+user.school+"</td>"+"<td>"+user.name+"</td>"+"<td>"+user.age+"</td>";
ul.append(li);
//放入页面
$("#table1").append(ul);
}
window.alert("查询成功");
}
});
});
</script>
</html>
txt文本文件内容
[{"school":"腾讯大学","name":"小腾","age":20},
{"school":"钉钉大学","name":"小丁","age":18},
{"school":"哔哩哔哩大学","name":"小利","age":19},
{"school":"哔哩哔哩大学","name":"小毕","age":19},
{"school":"哔哩哔哩大学","name":"小黎","age":19},
{"school":"腾讯大学","name":"小讯","age":18},
{"school":"钉钉大学","name":"小定","age":19},
{"school":"哔哩哔哩大学","name":"小碧","age":21}]
测试结果截图
新手制作不易,多多理解。