Q: 什么是ajax
A: 异步的javascript和xml(Asynchronous Javascript And XML )
Q: readyState有几种状态,各个状态各代表什么含义
👉有5中状态,各状态的含义如下
0 请求未初始化(代理被创建,但是尚未调用open()方法)
1 服务器连接已建立(open方法已经被调用)
2 请求已接收(send方法已经被调用,并且头部和状态已经可获得)
3 请求处理中(下载中,responseText 属性已经包含部分数据)
4 请求已完成,且响应已经就绪(下载操作已经完成)
Q: 说说常见的http状态码及其含义
http状态码 | 描述 |
100 | 继续。继续响应剩余部分,进行提交请求 |
200 | 成功 |
301 | 永久移动,请求资源永久移动到新位置 |
302 | 临时移动。请求资源临时移动到新位置 |
304 | 未修改。请求资源对比上次未被修改,响应中不包含资源内容 |
401 | 未授权,需要身份验证 |
403 | 禁止。请求被拒绝 |
404 | 未找到,服务器未找到需要资源 |
500 | 服务器内部错误。服务器遇到错误,无法完成请求 |
503 | 服务器内部错误。临时服务过载,无法处理请求 |
Q: 请写出原生ajax实现
// get请求
const xhr = new XMLHttpRequest();
xhr.open('get',`/login?userName=${this.userName}&pwd=${this.pwd}`,true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 || xhr.status === 304 ){
console.log(xhr.responseText)
}
}
}
xhr.send();
// post 请求
const xhr = new XMLHttpRequest();
xhr.open('post','/login',true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 || xhr.status === 304 ){
console.log(xhr.responseText)
}
}
}
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //默认编码
// xhr.setRequestHeader("Content-type","multipart/form-data"); //二进制编码
// xhr.setRequestHeader("Content-type","application/json"); //json编码
const data = {
userName : '张三',
pwd : '111111'
}
xhr.send(data);