定义数据:
data.json
{“user”:“taoxingrui”,“age”:19,“date”:“2019-09-23T02:56:49.478Z”,“money”:[1,2,3]}
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function getXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest()
}
else{
// 解决微软的特殊情况
new window.ActiveXObject('Microsoft.XMLHTTP')
}
}
// 异步请求服务器数据函数
function jsonData(){
var xhr = getXHR()
xhr .open('GET','data.json')
xhr.send(null)
// http://127.0.0.1:8020/htmlporject/day06/data.json
// 监听函数
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
// 得到服务器返回的json字符串
resp = xhr.responseText
console.log(resp)
htmlText = ""
// 解析字符串为json对象
jsonObj = JSON.parse(resp)
console.log(jsonObj)
// 组织显示HTML格式
htmlText = '<tr><td>' + jsonObj.user + '</td></tr>'
document.getElementById('userData').innerHTML = htmlText
htmlText = '<tr><td>' + jsonObj.age + '</td></tr>'
document.getElementById('ageData').innerHTML = htmlText
htmlText = '<tr><td>' + jsonObj.date + '</td></tr>'
document.getElementById('dateData').innerHTML = htmlText
htmlText = '<tr><td>' + jsonObj.money[0] + '</td></tr>'
document.getElementById('moneyData').innerHTML = htmlText
htmlText = '<tr><td>' + jsonObj.money[1] + '</td></tr>'
document.getElementById('moneyData1').innerHTML = htmlText
}
}
}
// function setInnerHTML(id, text){
// document.getElementById('id').innerHTML = htmlText
//}
</script>
</head>
<body>
<input type="button" name="" id="" value="加载" οnclick="jsonData()" />
<table border="1" cellspacing="" cellpadding="">
<thead>
<tr><th>用户名</th></tr>
</thead>
<tbody id="userData"></tbody>
</table>
<table border="2" cellspacing="" cellpadding="">
<thead>
<tr><th>年  龄</th></tr>
</thead>
<tbody id="ageData"></tbody>
</table>
<table border="3" cellspacing="" cellpadding="">
<thead>
<tr><th>时  间</th></tr>
</thead>
<tbody id="dateData"></tbody>
</table>
<table border="4" cellspacing="" cellpadding="">
<thead>
<tr><th>工  资</th></tr>
</thead>
<tbody id="moneyData"></tbody>
</table>
<table border="4" cellspacing="" cellpadding="">
<thead>
<tr><th>工  资</th></tr>
</thead>
<tbody id="moneyData1"></tbody>
</table>
</body>
</html>
效果
要不你也试试??