fetch和ajax的区别?

x33g5p2x  于2022-03-31 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(245)

一、写在前面
今天总结一下fetchajax的区别。
二、Ajax
ajax的本质就是使用XMLHttpRequest对象来请求数据,下面是简单的原生js实现。

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();
              }
           }
        }
    };
}

三、fetch
fetch是全局量window的一个方法,它的主要特点有:
1、第一个参数是URL.
2、第二个参数是可选参数,可以控制不同的配置的init对象。
3、使用了JavaScript Promises来处理结果/回调。

<script>
    fetch('http://123.207.32.32:8000/home/multidata').then(function(response) {
      console.log(response)
      return response.json()
    }).then(function(returnedValue) {
      console.log(returnedValue)
    }).catch(function(err) {
      console.log(err)
    })
</script>

四、fetch和ajax主要有两种方式不同
4.1、fetch()返回的Promise将不会拒绝http错误状态,即使相应是一个相应是400或者500,它都会安装正常的去解决,并且仅在网络故障时或者任何阻止请求完成时,它才会拒绝,可以做简单的封装。

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

4.2、默认情况下,fetch在不会接受和发送cookie,如果需要发送cookie的话,此时需要对其单独进行配置。

fetch(url, {
	credentials: 'same-origin'
})

same-origin值使得fetch处理cookieXMLHTTPRequest类似。否则,cookie将不会被发送,导致这些请求不保留认证会话。
对于cors请求,使用include值允许将凭证发送到其他域。

fetch(url, {
	credentials:'include'
})

相关文章

微信公众号

最新文章

更多