ajax requests for native js

Posted by Nile on Sun, 23 Jun 2019 21:47:19 +0200

Disadvantages of traditional methods:

The traditional web interaction is that the user triggers an http request server, and after the server receives it, it responds to the user and returns a new page. Whenever the server processes the request submitted by the client, the client can only wait idly, and even if it is only a small interaction and only needs to get a very simple data from the server, it must return a complete H. TML pages, and users waste time and bandwidth each time to re-read the entire page. This method wastes a lot of bandwidth, because every application interaction needs to send requests to the server, the response time of the application depends on the response time of the server. This leads to a much slower user interface response than local applications.

 

What is ajax

The emergence of AJAX has just solved the shortcomings of traditional methods. AJAX is a technology for creating fast dynamic web pages. AJAX enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that some parts of the page can be updated without reloading the entire page.

XMLHttpRequest object

The XMLHttpRequest object is the basis of ajax, and XMLHttpRequest is used to exchange data with the server in the background. This means that some parts of the page can be updated without reloading the entire page. Currently, all browsers support XMLHttpRequest

 

Method Description
abort() Stop the current request
getAllResponseHeaders() Returns all response headers of HTTP requests as key/value pairs
getResponseHeader("header") Returns the string value of the specified header
open("method","URL",[asyncFlag],["userName"],["password"])  Establish a call to the server. Method parameters can be GET, POST, or PUT. The URL parameter can be a relative or absolute URL. This method also includes three optional parameters, asynchrony, username, and password.
send(content) Send a request to the server
setRequestHeader("header", "value") Set the specified header to the value provided. You must call open() before setting any header. Set up the header and send it with the request ('post'method must)


Five-step usage:

1. Create an XMLHTTPRequest object

2. Use open method to set up interactive information with server

3. Set up the data to be sent and start interacting with the server

4. Registration Events

5. Update interface

Here are some examples of get and post requests

get request:

//Step 1:Create asynchronous objects
var ajax = new XMLHttpRequest();
//Step 2:Setting the request url parameter,The first parameter is the type of request,Parametric 2 is request url,It can take parameters.,Dynamic transfer parameters starName To the server
ajax.open('get','getStar.php?starName='+name);
//Step 3:Send requests
ajax.send();
//Step 4:Registration Events onreadystatechange If the state changes, it will be called
ajax.onreadystatechange = function () {
if (ajax.readyState==4 &&ajax.status==200) { //Step 5 If you can get into this judgment, the data will come back perfectly.,And the requested page exists
    console.log(xml.responseText);//Enter the appropriate content
  }
}

post request:

//Create asynchronous objects  
var xhr = new XMLHttpRequest();
//Set the type of request and url
//post Requests must be added to the request header, otherwise they will report errors.
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xhr.open('post', '02.post.php' );
//Send requests
xhr.send('name=fox&age=18');
xhr.onreadystatechange = function () {
    // This step is to determine whether the server responds correctly.
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.responseText);
  } 
};

In order to use it conveniently, we can encapsulate it in the method. When we want to use it, we can call it directly.

function ajax_method(url,data,method,success) {
    // Asynchronous object
    var ajax = new XMLHttpRequest();

    // get with post  You need to write different code separately
    if (method=='get') {
        // get request
        if (data) {
            // If there is value
            url+='?';
            url+=data;
        }else{

        }
        // Setting method and url
        ajax.open(method,url);

        // send that will do
        ajax.send();
    }else{
        // post request
        // post request url No need to change
        ajax.open(method,url);

        // Request message needs to be set
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");

        // judge data send send data
        if (data) {
            // If there is value from send Send out
            ajax.send(data);
        }else{
            // Wood value can be sent directly
            ajax.send();
        }
    }

    // Registration Events
    ajax.onreadystatechange = function () {
        // Get data in events and modify the interface display
        if (ajax.readyState==4&&ajax.status==200) {
            // console.log(ajax.responseText);

            // Make data available outside
            // return ajax.responseText;

            // When onreadystatechange The call indicates that the data is back
            // ajax.responseText;

            // If one can be introduced from outside function As a parameter success
            success(ajax.responseText);
        }
    }

}

Topics: Javascript PHP xml