[Difference] fetch front end and Ajax

One Ajax

Nature Ajax XMLHttpRequest object is used to request data, the following simple paste native js implemented:

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

Two fetch

fetch is a method overall volume window, its main features are:

  • The first parameter is the URL
  • The second is an optional parameter, the object can be controlled in different configurations init
  • Use a JavaScript Promises to process the results / callback

Three difference between the two

  • From the fetch () returns Promise HTTP error status will not be rejected, even if the response is a HTTP 404 or 500. Instead, it would be normal resolution (status is set to false wherein ok), and only when the network failure or blocked when any request is completed, it will be rejected.
  • By default, fetch does not send or receive any cookies on the server side, if the site is dependent on maintaining a user session, resulting in an unauthenticated request (to send cookies, credentials must be sent head). If you want to automatically send the same domain cookie, plus the credentials of the same-origin options for cors request, using the credentials include the option lets you send credentials to other domains.

Guess you like

Origin blog.csdn.net/cheidou123/article/details/93202291