Home > Web Front-end > JS Tutorial > body text

How to implement Ajax method in native js? Introduction to the method of implementing Ajax in native JS (with code)

青灯夜游
Release: 2018-10-23 17:37:23
forward
1959 people have browsed it

What this article brings to you is how to implement Ajax methods in native JS? Introduction to the method of implementing Ajax in native JS (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Generally speaking, everyone may be accustomed to using the Ajax method provided by JQuery, but how to implement the Ajax method using native js?

Ajax method provided by JQuery:

$.ajax({
    url: ,
    type: '',
    dataType: '',
    data: {
          
    },
    success: function(){
         
    },
    error: function(){
          
    }
 })
Copy after login

Native js implementation of Ajax method:

var Ajax={
  get: function(url, fn) {
    // XMLHttpRequest对象用于在后台与服务器交换数据   
    var xhr = new XMLHttpRequest();            
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
      // readyState == 4说明请求已完成
      if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { 
        // 从服务器获得数据 
        fn.call(this, xhr.responseText);  
      }
    };
    xhr.send();
  },
  // datat应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
  post: function (url, data, fn) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    // 添加http头,发送信息至服务器时内容编码类型
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
        fn.call(this, xhr.responseText);
      }
    };
    xhr.send(data);
  }
}
Copy after login

Comments:

1. open(method, url , async) method requires three parameters:

Method: The method used to send the request (GET or POST); compared with POST, GET is simpler and faster, and can be used in most cases ;However, please use POST requests in the following situations:

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

  • Sending large amounts of data to the server (POST has no data volume limit)

  • When sending user input containing unknown characters, POST is more stable and reliable than GET

 url: Specifies the URL of the 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 (can be on the server before returning the response) Execute tasks));

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

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

3. onreadystatechange: There is a function that handles 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 (# The ##open 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 some data)

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

5. responseText: Get the 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, just add parameters directly to the url, such as url?a =a1&b=b1.

PS: The basic principle of Fetch polyfill is to detect whether the window.fetch method exists, and if not, use XHR to implement it

The above is the detailed content of How to implement Ajax method in native js? Introduction to the method of implementing Ajax in native JS (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!