关于js中的ajax的使用总结,代码需要再服务器端运行~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax 1 - 请求纯文本</title>
</head>
<body>
<button id="button">请求纯文本</button>
<br><br>
<div id="text"></div>
<script>
document.getElementById('button').addEventListener("click",loadText);
function loadText(){
// console.log("Hello World!");
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// console.log(xhr);
// open(type,url/file,async)
xhr.open('GET','sample.txt',true);
// console.log("READYSTATE: ",xhr.readyState);
// onprogress
xhr.onprogress = function(){
// console.log("测试READYSTATE: ",xhr.readyState);
}
// 两种方式请求 onload / onreadystattechange
// xhr.onload = function(){
// // console.log("READYSTATE: ",xhr.readyState);
// // console.log(this.responseText);
// document.getElementById('text').innerHTML = this.responseText;
// }
xhr.onreadystatechange = function(){
// console.log("READYSTATE: ",xhr.readyState);
if (this.status == 200 && this.readyState == 4) {
// console.log(this.responseText);
document.getElementById('text').innerHTML = this.responseText;
}else if(this.status == 404){
// console.log("请求的网页不存在");
document.getElementById('text').innerHTML = "NOT Found";
}
}
// 发送请求
xhr.send();
}
// readyState 状态码
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
// HTTP 状态码
// 200 - 服务器成功返回网页
// 404 - 请求的网页不存在
// 503 - 服务器暂时不可用
</script>
</body>
</html>