readyState 状态码: 表示ajax请求的过程,ajax对象返回的
0:请求未初始化
1:服务器连接已建立
2:请求已接受
3:请求处理中
4:请求已完成,且响应已就绪
HTTP 状态码: 表示请求的处理结果,服务器返回的
200 - 服务器成功返回网页
404 - 请求的网页不存在
503 - 服务器暂时不可用
onreadystatechange() 的定义是只要返回的状态码只要变化时就回调一次函数 onload只有状态码为4时(请求已完成)才能回调一次函数 onprogress是当状态码为3时,会执行这个函数
需要结合http状态码和readyState 状态码进行判断
// 创建ajax对象
let xhr = new XMLHttpRequest();
// 设置请求方式和请求地址,boolean为是否异步请求
xhr.open('GET', 'ajaxTest.txt',true);
// 发送请求
//get请求是不能提交json对象格式数据
xhr.send();
// 监听响应 获取响应数据
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200)
{
console.log(`请求成功并返回数据${this.responseText}`);
}
}
let xhr = new XMLHttpRequest();
// post 请求
xhr.open('POST', 'ajaxTest.txt',true);
//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// post 请求可以提交JSON格式的参数
xhr.send(JSON.stringify({name:'张三'}));
// xhr.send('age=18&name=张三')
xhr.onload = function(){
if (xhr.status == 200)
{
console.log(`请求成功并返回数据${this.responseText}`);
}
else{
console.log(`请求不成功`);
}
console.log(`onload 状态码${xhr.readyState}`);
console.log(`这是onload函数请求的文本:${this.responseText}`);
}
ajax中的onload和readychange区别 - await - 博客园 (cnblogs.com)
ajax 运行原理及实现 onload/onreadystatechange 错误处理_tianmeng1999的博客-CSDN博客_xhr.onerror