JS原生XMLHttpRequest()异步请求数据

定义数据:

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>年&emsp;&emsp;龄</th></tr>
			</thead>
			<tbody id="ageData"></tbody>
		</table>
		<table border="3" cellspacing="" cellpadding="">
			<thead>
				<tr><th>时&emsp;&emsp;间</th></tr>
			</thead>
			<tbody id="dateData"></tbody>
		</table>
		<table border="4" cellspacing="" cellpadding="">
			<thead>
				<tr><th>工&emsp;&emsp;资</th></tr>
			</thead>
			<tbody id="moneyData"></tbody>
		</table>
		<table border="4" cellspacing="" cellpadding="">
			<thead>
				<tr><th>工&emsp;&emsp;资</th></tr>
			</thead>
			<tbody id="moneyData1"></tbody>
		</table>
	</body>
</html>

效果
在这里插入图片描述
要不你也试试??

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值