Home  >  Article  >  Web Front-end  >  What is the difference between ajax and fetch

What is the difference between ajax and fetch

青灯夜游
青灯夜游Original
2021-12-29 18:53:116449browse

Difference: 1. Fetch cannot natively monitor the progress of the request, while ajax is developed based on native XHR and can be monitored; 2. Compared with ajax, fetch has a better and more convenient writing method; 3. fetch only An error is reported for network requests, and 400 and 500 are regarded as successful requests, but ajax will not.

What is the difference between ajax and fetch

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

The difference between ajax and fetch:

(1) Ajax uses the XMLHttpRequest object to request data, while fetch is a window Method

(2). Ajax is developed based on native XHR. The structure of XHR itself is not clear. There is already an alternative to fetch

(3). Compared with ajax, fetch is better and more efficient. Convenient way of writing

(4), fetch only reports errors for network requests, and treats 400 and 500 as successful requests, which need to be encapsulated for processing

(5), fetch cannot natively monitor requests progress, and XHR can Maybe many people don't know how to write an ajax request themselves. They all use JQuery or Axios to request data

var xhr= new XMLHttpRequest(); // 新建XMLHttpRequest对象
xhr.onload= function(){ //请求完成
  console.log(this.responseText);
}
// 发送请求:
xhr.open('GET', '/user');
xhr.send();
Such a request is sent out. It's very troublesome. You have to write so many lines of code to send a simple request. Of course you won't write it like this in actual development, otherwise the code will be redundant and readable. Use promise to encapsulate it
var Ajax = {
    get: function(url,fn){
        // XMLHttpRequest对象用于在后台与服务器交换数据
        var xhr=new XMLHttpRequest();
        xhr.open('GET',url,false);
        xhr.onreadystatechange=function(){
            // readyState == 4说明请求已完成
            if(xhr.readyState==4){
                if(xhr.status==200 || xhr.status==304){
                    console.log(xhr.responseText);
                    fn.call(xhr.responseText);
                }
            }
        }
        xhr.send();
    },

    // data应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
    post: function(url,data,fn){
        var xhr=new XMLHttpRequest();
        xhr.open('POST',url,false);
        // 添加http头,发送信息至服务器时内容编码类型
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.onreadystatechange=function(){
            if (xhr.readyState==4){
                if (xhr.status==200 || xhr.status==304){
                    // console.log(xhr.responseText);
                    fn.call(xhr.responseText);
                }
            }
        }
        xhr.send(data);
    }
}

Code comments:

1,

open (method, url, async)

The method requires three parameters:

method: The method used to send the request (GET or POST); compared with POST, GET is simpler It is also faster and works in most cases; however, please use POST requests in the following situations:

①Cache files cannot be used (updating files or databases on the server)

②Send a large amount of data to the server (POST has no data limit)

③When sending user input containing unknown characters, POST is more stable and reliable than GET
  • url: Specifies the URL of a server-side script (the file can be any type of file, such as .txt and .xml, or a server script file, such as .asp and .php (which can perform tasks on the server before sending back a response ));

    async: Specifies that the request should be processed asynchronously (true) or synchronously (false); true means executing other scripts while waiting for the server to respond, and responding to the request when the response is ready Process; false means waiting for the server response before executing.

  • 2. The send() method can send the request to the server.

    3. onreadystatechange: There is a function that processes the server response. Whenever readyState changes, the onreadystatechange function will be executed.
  • 4. readyState: stores the status information of the server response.

0: The request is not initialized (the proxy is created, but the open() method has not been called)

1: The server connection is established (open The method has been called)

  • 2: The request has been received (the send method has been called, and the header and status are available)

  • 3: The request is being processed (downloading, the responseText attribute already contains part of the data)

  • 4: The request has been completed and the response is ready (the download operation has been completed)

  • 5.responseText: Obtain response data in string form.

  • 6.setRequestHeader(): When POST transmits data, it is used to add HTTP header, then send(data), pay attention to the data format; when GET sends information, directly add parameters to the url. Yes, for example url?a=a1&b=b1.

  • fetch usage
  • 1. The first parameter is the URL
  • 2. The second parameter can Selecting parameters can control different init objects
3. Use the promise object in js

var arr1 = [{
    name: "haha",
    detail:"123"
}];

    fetch("url", {
        method: "post",
        headers: {//设置请求的头部信息
            "Content-Type": "application/json"
            //跨域时可能要加上
            //"Accept":"allication/json"
        },    //将arr1对象序列化成json字符串
        body: JSON.stringify(arr1)//向服务端传入json数据
    }).then(function(resp) {
        resp.json().then((data) => {
                    
        })
    });
All IE browsers will not support the fetch() method, and the server will return status code 400 500 Will not reject【Related tutorial recommendation: AJAX video tutorial

The above is the detailed content of What is the difference between ajax and fetch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn