原生Ajax

67 阅读3分钟

一.Ajax是什么

AjAx是Asyncchronous JavaScript and XML(异步 JavaScript和XML)的简写

Ajax中的异步:可以异步的向服务器发送请求,在等待响应的过程中,不会阻塞当前页面,浏览器可以做自己的事情.直到成功获取响应后,浏览器才开始处理响应数据

XML(可扩展标记语言)是前后端数据通信时传输数据的一种格式 XML现在已经不怎么用了.现在比较常用的是JSON

Ajax其实就是浏览器与服务器之间的一种异步通信方式

使用Ajax可以在不重新加载整个页面的情况下,对页面的某部分进行更新

用途:网站注册检测,网站搜索提示

搭建Ajax开发环境

Ajax需要服务器环境,非服务器环境下,很多浏览器无法正常使用Ajax 安装 live Setver 插件搭建服务器 windows phpStudy 或 Mac MAMP 搭建服务器

二.基本用法

1.XMLHttpRequest

Ajax想要实现浏览器与服务器之间的异步通信,需要依靠XMLHttpRequest,他是一个构造函数 不论是XMLHttpRequest,还是Ajax,都没有和具体的某种数据格式绑定

2.Ajax的使用步骤

2.1实例化构造函数,创建XHR对象

const xhr = new XMLHttpRequest();

2.2监听事件,处理响应

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

xhr.onreadystatechange = () => {
          if (xhr.readyState !== 4) return;
          // HTTP CODE
          // 获取到响应后,响应的内容会自动填充xhr对象属性
          // xhr.status:HTTP 200 404
          // xhr.responseText:HTTP 状态说明 OK Not Found
          if ((xhr.status >= 200) & (xhr.status < 300) || xhr.status === 304) {
            console.log("正常使用响应数据");
            console.log(xhr.responseText);
          }
        };

readystatechange事件也可以配合addEventListener使用

不过要注意,IE6-8不支持addEventListener xhr.addEventListener('readystatechange',()=>{},false)

为了兼容性,readystatechange中不使用this,而是直接使用xhr 由于兼容性的原因,最好放在open之前

readystatechange事件监听readyState这个状态的变化
它的值从0~4,一共五个状态
0:未初始化,尚未调用open()
1:启动,已经调用open(),但尚未调用send()
2:发送,已经调用了send()但尚未接收到响应
3:接收,已经接收到部分响应数据
4:完成,已经接收到全部响应数据,而且可以在浏览器中使用了

2.3准备发送请求

          // 'HTTP方法GET、POST、DELERE',
          // '地址 URL https://www.imooc.com/api/http/search/suggest?word=js ./index.html ./index.xml ./index.txt',
          true
        );

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

2.4发送请求

调用send()正式发送请求

send()的参数是通过请求体携带的数据

xhr.send(null);

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

      const url = "http://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("正常使用响应数据");
          console.log(xhr.responseText);
        }
      };
      xhr.open('GET',url,true);
      xhr.send(null);

三.GET请求

1.携带数据

GET请求不能通过请求体携带数据,但可以通过请求头携带

2.数据编码

如果携带的数据是非英文字母,比如说汉字,就需要编码之后再发给后端,不然会造成乱码问题 可以使用encodeURIComponent()编码

const url = `http://www.imooc.com/api/http/search/suggest?words=${encodeURIComponent('前端')}`;
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState !== 4) return;
        if ((xhr.status >= 200) & (xhr.status < 300) || xhr.status === 304) {
          console.log("正常使用响应数据");
          console.log(xhr.responseText);
        }
      };
      xhr.open("GET", url, true);
      xhr.send(null);

四.POST请求

1.携带数据

POST请求主要通过请求体携带数据,同时也可以通过请求头携带

     const url =
          "http://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("正常使用响应数据");
            console.log(xhr.responseText);
          }
        };
        xhr.open("POST", url, true);
      // 如果想发送数据,直接卸载send()的参数位置,一般是字符串
      // xhr.send("username=alex&age=18");
      // 不能直接传递对象,需要先将对象转换成字符串的形式
      // xhr.send({
      //     username:'alex',
      //     age:18
      // });//->[object Object]

2.数据编码

xhr.send(username=${encodeURIComponent("张三")}&age=18);