Fecth与Ajax

126 阅读3分钟

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

作为一个前端开发者,我们基本都很熟悉AJAX了,AJAX可以说是前后端分离的的产物,我们通过它来进行前后端数据的交互,达到动态网页的效果(后台数据改变,无需再去修改HTML结构数据,自动更新网页中的数据内容)。

XMLHttpRequeste

AJAX依赖于浏览器的XMLHttpRequeste对象,我们发送一个 HTTP 请求,需要创建一个 XMLHttpRequest 对象,打开一个 URL,最后发送请求。当所有这些事务完成后,该对象将会包含一些诸如响应主体或 HTTP status 的有用信息。

我们来看一下发送一个Ajax的整个流程:

function ajax(url, fnSucc, fnFaild)
{
    //1.创建Ajax对象
    if(window.XMLHttpRequest){
       var oAjax=new XMLHttpRequest();
    }else{
       var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
    }

    //2.连接服务器(打开和服务器的连接)
    oAjax.open('GET', url, true);

    //3.发送
    oAjax.send();

    //4.接收
    oAjax.onreadystatechange=function (){
       if(oAjax.readyState==4){
           if(oAjax.status==200){
              //alert('成功了:'+oAjax.responseText);
              fnSucc(oAjax.responseText);
           }else{
              //alert('失败了');
              
              if(fnFaild){
                  fnFaild();
              }
           }
        }
    };
}

可以看见,我们如果只需要发送一个Ajax请求,需要写的代码的很多的。虽然很繁琐,但Ajax目前仍是主流的前后端通信的方案之一。

接下来介绍前后端通过的另一种方案fetch,它比起Ajax更加简便优雅。

Fetch返回的是一个Pormise,Fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。

Fetch两个特点

  1. 接口合理化,AJAX是将所有不同性质的接口都放在XHR对象上,而Fetch是将它们分散在几个不同的对象上,设计更合理
  2. Fetch操作返回Promise对象,避免了嵌套的回调函数。

接下来我们看一下Fetch发送一个Http请求的简单示例:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data) //获取到的数据);

可以看见使用Fetch发送Http请求比起Ajax而言是非常简便的。而且我们可以通过async、await来将异步回头改造成同步代码,便于我们的阅读。

对Fetch简单的封装为一个函数如下:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Fecth和Ajax的区别

  • fetch没有办法原生监测请求的进度,而ajax基于原生的XHR开发,可以监测;
  • 和ajax相比,fetch有着更好更方便的写法;
  • fetch只对网络请求报错,对400、500都当做成功的请求,而ajax不会。

Fecth还有很多其他配置,这里就不一一介绍了。