同步异步、状态码的变化、原生方法操作真实接口

98 阅读2分钟

 let xhr = new XMLHttpRequest();

/* 0: 请求未初始化(还没有调用到open方法) */

console.log('请求未初始化',xhr.readyState)

xhr.open('get', 'abc.txt', true)

xhr.send();

/* 1: 服务器连接已建立(已调用send方法,正在发生请求) */

console.log('服务器连接已建立',xhr.readyState)

/* onreadystatechange就是用来监听readyState值的变化的 */

xhr.onreadystatechange = function () {

/* 2: 请求已接收(send方法完成,已接收到全部响应内容) */

if(xhr.readyState == 2){

console.log('请求已接收',xhr.readyState)

}

/* 3: 请求处理中(解析响应内容) */

if(xhr.readyState == 3){

console.log('请求处理中',xhr.readyState)

}

/* 4: 请求已完成,且响应已就绪 */

if(xhr.readyState == 4){

console.log('请求已完成',xhr.readyState)

}

/* xhr.responseText 通过ajax请求获得的数据 */

// console.log(xhr.responseText)

console.log('响应状态码',xhr.status);

}

}

/* 响应状态码 */

/* status 为200 表示请求成功

201 也表示成功

304 从http请求中的缓存拿来的数据

*/

/* status 为404 not found 找不到地址 地址写错了 未找到页面

多数前端问题

403 表示没有权限*/

/* status 为500 表示服务端代码错误 */

【同步和异步】

setTimeout是一个异步操作 */

// setTimeout(function (){

// console.log(1)

// },0)

// console.log(2)

/* 平常写的代码都是同步的 */

console.log(1);

console.log(2);

【原生方法操作真实接口】

 这个真实的接口 是用来登录的

所以使用post方式登录

需要先判断有没有token 有token 就不提示直接获取数据

没有token 就给个提示 请先登录 获取token 不执行下面的内容

【请先登录,再获得数据】

if(!localStorage.token){

alert('请先登录,获取token!!')

return;

}

let xhr = new XMLHttpRequest();

/* pagenum=1 表示取第一页的数据 */

/* pagesize=5 表示显示5条数据 */

let url = 'timemeetyou.com:8889/api/private…';

xhr.open('get', url, true);

xhr.setRequestHeader('Authorization',localStorage.token)

xhr.send();

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

let res = JSON.parse(xhr.responseText)

console.log(res);

}

}

【获取用户数据】

 let xhr = new XMLHttpRequest();

let url = 'timemeetyou.com:8889/api/private…';

xhr.open('post', url, true);

let params = {

username: "admin",

password: "123456"

}

/* post需要添加请求头 */

/* 请求回来的内容是json格式 */

/* Content-type 表示请求内容的类型 */

/* application/json 表示请求内容的类型的具体的值 */

xhr.setRequestHeader("Content-type", "application/json")

xhr.send(JSON.stringify(params));

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

let res = JSON.parse(xhr.responseText)

console.log(res);

localStorage.token = res.data.token;

// location.href="shop.html"

}

}