Ajax使用步骤

1.XMLHttpRequest

Ajax 想要实现浏览器与服务器之间的异步通信,需要依靠 XMLHttpRequest,它是一个构造函数

不论是 XMLHttpRequest,还是 Ajax,都没有和具体的某种数据格式绑定

2.Ajax 的使用步骤

2.1.创建 xhr 对象

const xhr = new XMLHttpRequest();

2.4.(先看2.2、2.3)监听事件,处理响应

当获取到响应后,会触发 xhr 对象的 readystatechange 事件,可以在该事件中对响应进行处理

​ readystatechange 事件监听 readyState 这个状态的变化

它的值从 0 ~ 4,一共 5 个状态

0:未初始化。尚未调用 open()

1:启动。已经调用 open(),但尚未调用 send()

2:发送。已经调用 send(),但尚未接收到响应

3:接收。已经接收到部分响应数据

4:完成。已经接收到全部响应数据,而且已经可以在浏览器中使用了

 xhr.onreadystatechange = () => {if (xhr.readyState !== 4) return; //判断是否已经接收全部响应数据// HTTP CODE// 获取到响应后,响应的内容会自动填充 xhr 对象的属性// xhr.status:HTTP状态码// xhr.statusText:HTTP 状态说明(无实际意义)if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {// 正常使用响应数据

​     console.log(xhr.responseText);//responseText响应数据}

   };


readystatechange 事件也可以配合 addEventListener 使用,不过要注意,IE6~8 不支持 addEventListener

为了兼容性,readystatechange 中不使用 this,而是直接使用 xhr

由于兼容性的原因,2.4 事件监听最好放在 2.2 open 之前

2.2.准备发送请求

xhr.open(‘HTTP 方法 GET、POST、PUT、DELETE’,‘地址 URL https://www.imooc.com/api/http/search/suggest?words=js ./index.html ./index.xml ./index.txt’,true);

​ 第三个参数代表是否异步,一般只用true异步

调用 open 并不会真正发送请求,而只是做好发送请求前的准备工作

2.3.发送请求

调用 send() 正式发送请求,send() 的参数是通过请求体携带的数据

xhr.send(null); //使用get方法时参数为null或者不填

3.使用 Ajax 完成前后端通信

const url = 'https://www.imooc.com/api/http/search/suggest?words=js';



 const xhr = new XMLHttpRequest();

 xhr.onreadystatechange = () => {if (xhr.readyState !== 4) return;if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {

​     console.log(xhr.responseText);   //此处获取到的响应数据是JSON格式的,需要对它进行解析(JSON.parse())等操作才可以在JS中使用

​     console.log(typeof xhr.responseText);}

 };

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

 xhr.send(null);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值