小言_互联网的博客

简单的ajax请求响应

244人阅读  评论(0)

简单的ajax请求响应

今天学习了简单的ajax应用,以下是一个简单的ajax请求响应程序

<!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()
				//通过get方法,访问data.json文件
				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="加载" onclick="jsonData()"/>
		
		<table border="1">
			<thead>
				<tr><th>用户名</th></tr>
			</thead>
			<tbody id='userData'></tbody>
		</table>
	</body>
</html>

代码效果:点击加载按钮,得到用户信息


转载:https://blog.csdn.net/g1x2w3/article/details/101202503
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场