Data request ajax, Ajax, jQuery ajax, the difference between axios and fetch

Axios, Ajax, jQuery Ajax, and Fetch are all tools used to send data requests in JavaScript , but there are the following differences between them:

1: Axios:

    axios is a promise-based HTTP library that can be used in browsers and node.js.
    Features:
        Create XMLHttpRequests from the browser,
        create http requests from node.js,
        support Promise API
        interception of requests and responses,
        convert request data and response data,
        cancel requests,
        automatically convert JSON, data
        client supports defense against CSRF   
        transmission and download progress, etc.               

        The following is the basic usage of sending a GET request using Axios:

        1. Install Axios

npm install axios

        2.Introducing Axios

import axios from 'axios'

        3.Send GET request

axios.get('/api/user')
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {
    console.log(error)
  })

        In the above code, we send a GET request through the axios.get() method and specify the requested URL. When the request is successful, we response.dataobtain the response data through. If the request fails, we can catch the error through catch() and handle it accordingly.

        In addition to GET requests, Axios also supports sending POST, PUT, DELETE and other requests. The method names are different from GET, but the specific usage is similar.

        Axios also supports setting request headers, request parameters, request interceptors, response interceptors and other features. You can learn more about usage through the official documentation.                                        

Second: Ajax:

        Ajax is a technology that uses the XMLHttpRequest object to exchange data with the server. It can load data asynchronously without blocking other operations on the page. However, when using Ajax, you need to manually handle some errors, such as request timeout, network errors, etc.

       Native Ajax usage is slightly more complicated than jQuery, and requires manual processing of various properties and methods of the XMLHTTPRequest object. The following is a basic GET request:

// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();

// 设置请求地址
xhr.open('GET', '/api/user');

// 监听状态改变事件
xhr.onreadystatechange = function() {
  // 如果请求已完成
  if (xhr.readyState === 4) {
    // 如果请求成功
    if (xhr.status === 200) {
      // 获取响应数据并进行处理
      console.log(xhr.responseText);
    } else {
      // 请求失败,输出错误信息
      console.log(xhr.status + ' ' + xhr.statusText);
    }
  }
};

// 发送请求
xhr.send();

        In the above code, we first create an XMLHttpRequest object, and then call the open() method to set the request address. Next, we listened to the onreadystatechange event, which is triggered when the readyState property of the XMLHttpRequest object changes. When readyState equals 4, it means that the request has been completed. At this time, you can judge whether the request is successful based on the status attribute. If successful, you can get the response data through the responseText attribute. Finally, call the send() method to send the request.

        In addition to GET requests, native Ajax also supports sending POST, PUT, DELETE and other requests. The specific usage is similar to jQuery. Native Ajax also supports setting request headers, request parameters, request types, timeouts and other features. You need to manually set the corresponding properties. 

Three: jQuery Ajax

        jQuery Ajax is based on Ajax encapsulation, which is simple and convenient to use, but it needs to introduce the jQuery library into the code.

          The following is the basic usage of using jQuery to send a GET request:

        1.Introduce jQuery

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

        2.Send GET request

$.ajax({
  url: '/api/user',
  type: 'GET',
  success: function(response) {
    console.log(response)
  },
  error: function(xhr, status, error) {
    console.log(error)
  }
})

        In the above code, we send a GET request using the $.ajax() method and specify the requested URL. When the request is successful, we obtain the response data through the success callback. If the request fails, we can catch the error through the error callback and handle it accordingly.

        In addition to GET requests, Ajax also supports sending POST, PUT, DELETE and other requests. The method names are different from GET, but the specific usage is similar.

        Ajax also supports setting request headers, request parameters, request types, timeouts and other features. You can learn more about its usage through the jQuery official documentation.

Four: Fetch 

        Fetch is a new API in ES6. It is implemented based on Promise object and can replace XMLHttpRequest object. Fetch has more powerful functionality and simpler syntax. However, Fetch is more troublesome when handling errors, and some errors need to be handled manually.

The following is a basic GET request:

fetch('/api/user')
  .then(response => {
    // 如果请求成功
    if (response.ok) {
      // 获取响应数据并进行处理
      return response.json().then(data => console.log(data));
    } else {
      // 请求失败,输出错误信息
      console.log('网络请求失败');
    }
  })
  .catch(error => {
    // 请求过程中出现异常
    console.error(error);
  });

        In the above code, we call the fetch() method to send the request and return a Promise object. In the callback function of the Promise object, we can determine whether the request is successful based on the status attribute of the response. If successful, we can call the response.json() method to obtain the response data and process it. In the catch() method of the Promise object, we can handle exceptions that occur during the request.

        In addition to GET requests, the Fetch API also supports sending POST, PUT, DELETE and other requests. The specific usage is similar to jQuery. The Fetch API also supports setting request headers, request parameters, request types, timeouts and other features. You need to manually set the corresponding parameters. It should be noted that since the Fetch API is based on Promise, the CORS protocol needs to be used when processing cross-domain requests, otherwise cross-domain requests will be rejected by the browser.

Five: The difference between Ajax, jQuery ajax, axios and fetch:

Ajax:

       Needless to say, ajax is the earliest technology for sending back-end requests. It belongs to the original js. The core uses the XMLHttpRequest object. If there is a sequential relationship between multiple requests, callback hell will occur.

Jquery Ajax:

      It is a technology for sending back-end requests in the jQuery framework. Since jQuery is encapsulated based on the original, jquery Ajax is naturally also an encapsulation of the original ajax.

Fetch:

     Fetch is known as a replacement for AJAX. It appeared in ES6 and uses the promise object in ES6. Fetch is designed based on promises. The code structure of Fetch is much simpler than ajax, and the parameters are a bit like jQuery ajax. However, you must remember that fetch is not a further encapsulation of ajax, but native js. The Fetch function is native js and does not use the XMLHttpRequest object.

axios:

    Axios is not native JS and needs to be installed. It can be used on the client side or on the nodejs side. Axios can also intercept during the request and response phases. It is also based on promise objects. Specifically refer to the concept of axios


Summary: Axios is more powerful than Ajax and jQuery Ajax, while Fetch is a newer and more advanced API, but it also has some problems. Choosing a tool that suits your needs can improve code writing efficiency and reduce the risk of errors.

Guess you like

Origin blog.csdn.net/weixin_40381947/article/details/131376626