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

How to implement Ajax in native js

小云云
Release: 2018-03-31 16:48:52
Original
1163 people have browsed it

Generally speaking, everyone may be accustomed to using the Ajax method provided by JQuery, but how to implement the Ajax method using native js? This article mainly shares with you the method of implementing Ajax in native js. I hope it can help you.

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

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 and faster, and can be used in most cases; however, Use POST requests in the following situations:

  • Unable to use cached files (updating files or databases on the server)

  • Send to the server Large amounts of data (POST has no data size 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 (which can perform tasks on the server before returning the 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 processing the response when the response is ready; false means waiting for the server Response and then execution.

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

Related recommendations:

JS example code for implementing Ajax

Native JS implements ajax and ajax cross-domain requests

AngularJS method to implement ajax request

The above is the detailed content of How to implement Ajax in native js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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!