原生AJAX请求
目录
一、GET请求
步骤:
1.创建对象
const xhr = new XMLHttpRequest();
2.初始化 设置请求方法和url
xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');//用&符号连接
3.发送(可不写内容)
xhr.send();
4.事件绑定 处理服务端返回的结果
//on 当......的时候
//readystate 是 xhr 对象中的属性,表示状态0 1 2 3 4
//change 改变
xhr.onreadystatechange = function () {
//判断(服务端返回了所有的结果)
if (xhr.readyState === 4) {
//判断响应的状态200 404 403 401 500
//响应中2xx 表示成功
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 行 头 空行 体
//1.响应行
/*console.log(xhr.status);//状态码
console.log(xhr.statusText);//响应状态字符串
console.log(xhr.getAllResponseHeaders());//所有的响应头
console.log(xhr.response);//响应体*/
//设置 result 的文本
result.innerHTML=xhr.response;
}
}
}
二、POST请求
步骤:
1.创建对象(跟以上get请求一样)
2.初始化 设置类型和 url
xhr.open('POST', 'http://127.0.0.1:8000/server');
//设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
3.发送
xhr.send('a=100&b=200&c=300');
// xhr.send('a:100&b:200&c:300');
4.事件绑定
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理服务端返回的结果
result.innerHTML = xhr.response;
}
}
}
三、响应JSON数据
步骤:
1.创建对象(跟以上get请求一样)
2.设置响应体的数据
xhr.responseType='json';
3.初始化
xhr.open('GET', 'http://127.0.0.1:8000/json-server');
4.发送(跟以上get请求一样)
5.事件绑定
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理服务端返回的结果
// result.innerHTML = xhr.response;
//手动对数据进行转化
// let data = JSON.parse(xhr.response)
// result.innerHTML = data;
//自动对数据进行转化
result.innerHTML = xhr.response.name;
}
}
}
四、网络超时和异常
步骤:
1.创建对象(跟以上get请求一样)
2.设置超时设置 2s
xhr.timeout = 2000;
3.设置回调
// 超时回调
xhr.ontimeout = function () {
alert('网络异常,请稍后重试')
}
// 网络异常回调
xhr.onerror=function(){
alert('你的网络似乎出了一些问题')
}
4.初始化
xhr.open('GET', 'http://127.0.0.1:8000/delay')
5.事件绑定
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
五、取消请求
<body>
<button>点击发送</button>
<button>点击取消</button>
<script>
const btn = document.querySelectorAll('button')
let x = new XMLHttpRequest();
btn[0].addEventListener('click', function () {
x.open('GET', 'http://127.0.0.1:8000/delay');
x.send();
})
btn[1].addEventListener('click', function () {
x.abort();
})
</script>
</body>
六、重复请求问题
<body>
<button>点击发送</button>
<script>
const btn = document.querySelectorAll('button')
let x=null;
// 标志变量
let isSending = false; //是否正在发送AJAX请求
btn[0].addEventListener('click', function () {
if(isSending)// 如果正在发送则取消AJAX请求
x.abort();
x = new XMLHttpRequest();
isSending = true;
x.open('GET', 'http://127.0.0.1:8000/delay');
x.send();
x.onreadystatechange = function () {
if (x.readyState === 4) {
isSending = false;
}
}
})
</script>
</body>
版权声明:本文为weixin_63443072原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。