Ajax的基本使用

146 阅读1分钟

ajax的基本使用

1.创建对象

const xhr = new XMLHttpRequest();

2.初始化,设置请求:方法、url

xhr.open('请求方式', 'url');

3.发送

xhr.send();

4.事件绑定 处理服务端返回的结果

xhr.onreadystatechange = function () {}
// on当...的时候 
// ready state 是xhr对象中的属性  表示状态 0,1,2,3,4
// change 改变的时候触发

5.判断服务端返回了所有的结果

if (xhr.readyState == 4) {}               

6.判断响应状态码 2开头的为成功

 if (xhr.status == 200) {}

7.处理服务端返回的结果

xhr.status 状态码
xhr.statusText 状态字符串 
xhr.getAllResponseHeaders 响应头
xhr.response 响应体

json转换

手动转换,send()只接收字符串和buff

可以通过JSON.stringfy()将json文件转换为json格式的字符串
在来html页面用JSON.parse()将字符串转换为对象

自动转换

设置响应体数据类型
xhr.responseType='json';

输出

dom对象.innerHTML = xhr.response.xx;

自动重启服务

nodemon .\xxx