AJAX数据请求

ajax数据请求需要四个步骤:(请求文本内容)

1.创建XMLHttpRequest对象;

2.打开与服务起的链接;

3.发送给服务器;

4.响应就绪。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>ajax请求数据</title>
	</head>
	<body>
		<button id="btn">请求数据</button>
		<h1 id="txt"></h1>
		<script type="text/javascript">
			var btn = document.getElementById('btn');
			var txt = document.getElementById('txt');
			btn.onclick = function() {
				//1.创建XMLHttpRequest对象
				var xhr = null;
				if(window.XMLHttpRequest) {//非IE56
					xhr = new XMLHttpRequest();//实例对象
				}else {//IE56
					xhr = new ActiveXObject('Microsoft.XMLHTTP');
				}
				//2.打开与服务器的链接
				xhr.open('get','abc.txt',true);
				//3.发送给服务器
				xhr.send(null);//get请求
				//4.响应就绪
				xhr.onreadystatechange = function() {
					if (xhr.readyState == 4) {//请求完成
						if(xhr.status == 200) {
							txt.innerHTML = xhr.responseText;
						}else {
							alert(xhr.status);
						}
					}
				}
			}
		</script>
	</body>
</html>

 

原文地址:https://www.cnblogs.com/handsomehan/p/5864932.html