Encapsulate your own general Ajax

Time:2021-5-11

A simple ajax request

First, we need to know how to implement a simple ajax request before encapsulating our own Ajax function.

Here I created two files, ajax01. HTML and ajax01. PHP

Ajax01.html Code:

<!doctype html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Ajax</title>
</head>
<body>
   < input type = button "id = getcontent" value = click me to get the content / >
   < div id = "container" > click the above button, I will change < / div >
</body>

<script>
/*********************************ajax**********************************/
    //Get element
   var getContent = document.getElementById("getContent");
   var container = document.getElementById("container");
   var user_info = document.getElementById("user_info");
   

   //Add a click event handler to an element
   getContent.onclick = function (){
       //1. Create XHR object
       var xhr = new XMLHttpRequest();
       
       //4. Add a state change event handler to the request
       xhr.onreadystatechange = function (){
           //Judgment status code
           if(xhr.status==200 && xhr.readyState==4){
               //The returned JSON data is parsed and saved in the variable res
               var res = JSON.parse(xhr.responseText);
               container.innerHTML = res.name;
           }
       };

       //2. Initialization request
       XHR. Open ('Get ',' ajax01. PHP? Name = Zhang San & age = 16 ', true');
       //If it is a post request, you need to set the request header
       //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       

       //3. Send request
       xhr.send(null);
   
   };
</script>
</html>

You can see that using Ajax to send a request and get the response data only takes four simple steps

Parameter Description:

Xhr.status ——– status: HTTP status of the response. 200 indicates that the response is successful

Xhr.readystate ——- readyState this attribute represents the current activity stage of the request / response process. The values of this attribute are as follows:

0: not initialized. The open() method has not been called.
1: Start. The open() method has been called, but the send() method has not been called.
2: Send. The send() method has been called, but no response has been received.
3: Receive. Partial response data has been received.
4: Done. All response data has been received and can be used in the client.

Xhr.onreadystatechange ——– readyState property state change event. As long as the readyState property value changes from one value to another, a readystatechange event will be triggered. You can use this event to detect the readyState value after each state change.

XHR. ResponseText ——– responseText: the text returned as the response body.

Xhr.responsexml ——– responsexml: if the content type of the response is “text / XML” or “application / XML”, this attribute will save the XML DOM document containing the response data

It should be noted that when using Ajax to send a post request, the content type header information should be set to application / x-www-form-urlencoded, as follows:

xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

The header information setting must be set after the open () method and before the send method. The code is as follows:

//Initialization request
xhr.open('post','ajax01.php',true);

//If it is a post request, you need to set the request header
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       
//Send the request. If you want to send the data, pass the data into the send method
XHR. Send ('name = Zhang San & age = 16 ');

If you want to send data, pass the data into send()

The code in ajax01.php is as follows:

<?php

if(empty($_POST)){
   //Receive the get request parameter, and format the data as a JSON string and return it to Ajax
   echo json_encode($_GET);
}else{
   //Receive the post request parameters, and format the data as a JSON string and return it to Ajax
   echo json_encode($_POST);
}


?>

Now that we know how to use ajax to make a simple request, we can package our own general Ajax function

Encapsulate your own general Ajax functions
Less gossip, let’s go straight to the code

/*
*Encapsulate your own Ajax function
*There are five parameters, the last one is optional
*
*@ param method (required) request types get and post
*@ param URL (required) the requested URL address is the page under the same domain name (this function does not support cross domain requests)
*@ param data (required) the requested data is defined in the form of JS object, such as: {Name: 'Zhang San'}
*The @ param callback (required) callback function can receive a parameter, which is the response data of the server
*@ param type (optional) specifies the data type of the server response (optional values: JSON, XML, text). If it is in JSON mode, it uses JSON to parse the data, and the default is text
*/
function myAjax(method,url,data,callback,type){
   //Create a compatible XMLHttpRequest object
   var xhr;
   if (window.XMLHttpRequest){//IE7+, Firefox, Chrome, Opera, Safari
     xhr=new XMLHttpRequest();
   }else{// code for IE6, IE5
     xhr=new ActiveXObject("Microsoft.XMLHTTP");
   }

   //Add a state change event handler to the request
   xhr.onreadystatechange = function (){
       //Judgment status code
       if(xhr.status==200 && xhr.readyState==4){
           //According to the type parameter, judge how to deal with the returned content
           if(type=='json'){
               //Get the response data in the form of JSON, and use the parse method to parse
               var res = JSON.parse(xhr.responseText);
           }else if(type=='xml'){
               //Get the response data in XML form
               var res = responseXML;
           }else{
               //Get the response data in string form
               var res = xhr.responseText;
           }
           //Call the callback function and pass the response data into the callback function
           callback(res);
       }
   };
   
   //Judge whether there is data in data
   var param = '';
   //Here, we use the stringify method to format the JS object as a JSON string
   if(JSON.stringify(data) != '{}'){
       url += '?';
       for(var i in data){
           param += i+'='+data[i]+'&';   // Reorganize JS objects, splice them into URL parameters and store them in param variables
       }
       //Use slice function to extract part of the string, here is mainly to remove the last & character of splicing
       //Slice function: returns a new string. Include all characters of the string from start (including start) to end (excluding end).
       param = param.slice(0,param.length-1);  
   }

   //Judge whether method is get
   if(method == "get"){
       //If yes, the data is spliced behind the URL
       url = url+param;
   }


   //Initialization request
   xhr.open(method,url,true);

   //If method = = post
   if(method == "post"){
       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       //Send request
       xhr.send(param);
   }else{
       //Send request
       xhr.send(null);
   }
   
}

After encapsulating our own Ajax function, let’s make a request with this function

<!doctype html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Ajax</title>
</head>
<body>
   < input type = button "id = getcontent" value = click me to get the content / >
   < div id = "container" > click the above button, I will change < / div >
</body>


<script>
    //Get element
   var getContent = document.getElementById("getContent");
   var container = document.getElementById("container");
   var user_info = document.getElementById("user_info");
   
   //Add a click event handler to an element
   getContent.onclick = function (){
       //Send a post request using your own encapsulated Ajax function
       Myajax ('post ','ajax01. PHP', {Name: 'Zhang San', age:16 },function(res){
           console.log(res);
           container.innerHTML = res.name;
       },'json');
   };
</script>
</html>

The effect is as follows:

Encapsulate your own general Ajax
Encapsulate your own general Ajax
Here we can use the encapsulated Ajax function normally, which is much more convenient than using native JS to write so much code. Now we just need to call this Ajax function to send the request conveniently.

Recommended Today

Order by sorting optimization

In daily business development, order by is indispensable. But to write efficient sorting SQL, we need to spend some energy and time to understand the underlying principle of sorting, so as to find a good strategy to optimize the sorting. How to sort Index (index sort, best performance) Use index fields to sort as much […]