简单的ajax请求响应

简单的ajax请求响应

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


<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 = '' + jsonObj.user + ''
						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>

代码效果:点击加载按钮,得到用户信息
简单的ajax请求响应_第1张图片

你可能感兴趣的:(简单的ajax请求响应)