ajax工作流程图:
index.html
<!DOCTYPE html>
<html>
<head>
<title>ajax - 请求纯文本</title>
</head>
<body>
<button id="btn">请求纯文本</button>
<p id="text"></p>
</body>
</html>
js
<script>
document.getElementById(‘btn‘).addEventListener(‘click‘,loadText);
let text = document.getElementById(‘text‘);
function loadText(){
// 1 创建XMLHTTPRequest对象,用于连接客户端与服务端
let xhr = new XMLHttpRequest();
// console.log(xhr);
// 2
xhr.open(‘GET‘,‘./sample.txt‘,true);
// 3 请求的方式(两种)onload() 和 onreadystatechange()
// readyState 状态码
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
//
// HTTP 状态码
// 200 - 服务器成功返回网页
// 404 - 请求的网页不存在
// 503 - 服务器暂时不可用
// 3.1
xhr.onload = function(){
if (this.status == 200 && this.readyState == 4) {
console.log(this.readyState);
console.log(this.responseText);
}
}
// 3.2
// xhr.onreadystatechange = function(){
// if (this.status == 200 && this.readyState == 4) {
// text.innerHTML = this.responseText;
// }else if(this.status == 404){
// console.log(‘网页不存在!!‘);
// }
// }
// 4 发送请求
xhr.send();
}
</script>
原文:https://www.cnblogs.com/woshinixxk/p/11687342.html