追加到表格.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table width="500" border="1">
<tr>
<th>姓名
<th>年龄
<th>性别
</tr>
</table>
<button>点击
<script src="ajax3.0-min.js">
<script>
// 需求:当点击button按钮的时候,获取服务器的数据,并追击到table表格中
// 1.获取table表格
var table = document.getElementsByTagName('table')[0];
var btn = document.getElementsByTagName('button')[0];
// 2.点击事件
btn.onclick = function() {
// ajax获取数据:是一个对象,需要在Ajax()函数传递"JSON"的参数,约束了msg是对象类型的数据
Ajax('JSON').get('2.json', function(msg) {
console.log(msg);
// console.log(typeof msg);
var str = '';
for (var i = 0; i < msg.length; i++) {
str += '';
str += '' + msg[i]['username'] + '';
str += '' + msg[i]['age'] + '';
str += '' + msg[i]['sex'] + '';
str += '';
}
// 将拼装的字符串写入到table中
table.innerHTML += str;
})
}
</script>
</body>
</html>
2.json
[
{ "username": "张三", "age": 30, "sex": "\u7537" },
{ "username": "\u7545\u7545", "age": 28, "sex": "\u5973" },
{ "username": "\u5cf0\u54e5", "age": 36, "sex": "\u7537" },
{ "username": "\u5cf0\u54e5\u5ac2\u5b50", "age": 44, "sex": "\u5973" }
]