JS: AJAX使用原生XMLHttpRequest对象请求服务器JSON数据

1、data.json数据定义:

{"user":"lisi","age":19,"date":"2019-09-23T02:56:08.650Z","money":[1,2,3,4,5]}

2、代码实现

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			// js里XMLHttpRequest类似于python里的requests、urlib
			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)
				
				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 
					}
				} 
			}
		</script>
	</head>
	<body>
		<input type="button" value="加载" οnclick="jsonData()"/>
		
		<table border="1">
			<thead>
				<tr><th>用户名</th></tr>
			</thead>
			<tbody id='userData'></tbody>
		</table>
	</body>
</html>
发布了34 篇原创文章 · 获赞 54 · 访问量 5028

猜你喜欢

转载自blog.csdn.net/nosprings/article/details/101199672