ajax的由来

141 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

传统项目前后端不分离的,用户触发一个http请求服务器,服务器接受到请求之后,响应一个页面或字符串给浏览器,浏览器会刷新。

之前的前后端交互都是通过页面刷新或页面跳转来实现的。

场景

视频网站下方会有留言功能(评论区)

使用Ajax,可以不用重新请求整个页面而获取部分数据的效果(不用刷新页面,就可以获取数据。)

之前:html css js 数据。

ajax:数据

ajax特点

1.不需要插件支持。(原生js就支持)

2.用户体验佳(不需要刷新页面了)

3.减轻服务器的压力。提高web程序的性能。

ajax使用

1.准备xmlhttprequest对象。

2.调用对象的open方法 (打开连接)

3.调用对象的send方法(发送请求)

4.监听状态的改变。(接受服务器的响应)

代码

 <button onclick="sendMsg()">发送请求</button>
   <div class="box">
     接受的信息:<span id="msg"></span>
   </div>
  <script>
    const msg = document.querySelector("#msg")
    function sendMsg(){
      // 1.准备xmlhttprequest对象
      let xhr = new XMLHttpRequest();
      // 2.open方法的三个参数:
        //1.请求方式  get post push
        //2.请求的url 
        //3.是否异步  默认值为true 异步 。(一般不用第三个参数)
      xhr.open("get","http://127.0.0.1:3000/index");
      // 3.调用对象的send方法
      xhr.send();
      // 4.监听状态的改变。
      xhr.onreadystatechange = function(){
        //状态的值由5种  0-4  4代表最终的成功。
        // 还要判断服务器的响应码  200表示响应成功。
        if (xhr.readyState == 4 && xhr.status == 200) {
          //真正的成功
          msg.innerHTML = xhr.responseText;
        }
      }
    }

ajax post请求

  const msg = document.querySelector("#msg")
    function sendMsg(){
      // 1.准备xmlhttprequest对象
      let xhr = new XMLHttpRequest();
      // 2.open方法的三个参数:
        //1.请求方式  get post push
        //2.请求的url 
        //3.是否异步  默认值为true 异步 。(一般不用第三个参数)
      xhr.open("post","http://127.0.0.1:3000/add");
      // 3.调用对象的send方法
      xhr.send();
      // 4.监听状态的改变。
      xhr.onreadystatechange = function(){
        //状态的值由5种  0-4  4代表最终的成功。
        // 还要判断服务器的响应码  200表示响应成功。
        if (xhr.readyState == 4 && xhr.status == 200) {
          //真正的成功
          msg.innerHTML = xhr.responseText;
        }
      }
    }

get和post参数的不同

   const msg = document.querySelector("#msg");
    function sendMsg(){
      // 1.准备xmlhttprequest对象
      let xhr = new XMLHttpRequest();
      // xhr.open("get","http://127.0.0.1:3000/getParams?id=1");
      xhr.open("post","http://127.0.0.1:3000/postParams");
      //post请求 发送参数需要设置请求头。
      xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      
      xhr.send("name=薇娅");
      // 4.监听状态的改变。
      xhr.onreadystatechange = function(){
        //状态的值由5种  0-4  4代表最终的成功。
        // 还要判断服务器的响应码  200表示响应成功。
        if (xhr.readyState == 4 && xhr.status == 200) {
          //真正的成功
          msg.innerHTML = xhr.responseText;
        }
      }
    }

封装ajax

 <!-- 
    封装ajax,要确定4个参数:
      1.请求方式
      2.请求地址
      3.请求参数
      4.回调函数
   -->
  <script>
    var p = {
      name:"薇娅",
      msg:"九万年13个亿",
      age:36
    }
    // ==> "name='薇娅'&msg='九万年13个亿'&age=36"
    /**
     * 封装的ajax 请求
     * @param {string} type 请求方式
     * @param {string} url 请求地址
     * @param {object} params 参数
     * @param {Function} callBack 回调函数
     */
    function ajax(type, url, params, callBack) {
      let paramsStr = "";
      if (params) {
        let arr = [];
        for (const k in params) {
          arr.push(`${k}='${params[k]}'`)
        }
        //将数组中的每一个元素用 & 号拼接
        paramsStr = arr.join("&");
      }
      let xhr = new XMLHttpRequest();
      
      if (type == "get") {
        xhr.open(type,url+"?"+paramsStr);
        xhr.send();
      } else {
        //post请求 发送参数需要设置请求头。
        xhr.open(type,url)
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(paramsStr);
      }
      
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          
          //执行回调函数
          if (callBack) {
            //响应的结果: xhr.responseText
            callBack(xhr.responseText)
          }
        }
      }
    }
    // ajax("get","http://127.0.0.1:3000/index",p,(data)=>{
    //   // document.body.innerHTML = data;
    //   console.log(data);
    // });
    ajax("post","http://127.0.0.1:3000/postParams",p,(data)=>{
      document.body.innerHTML = data;
      // console.log(data);
    });