AJAX is what

AJAX is a technique for exchanging data with the server and updating parts of a web page without reloading the entire page.

Steps to create an AJAX request

window.onload=function(){
   var oBtn = document.querySelector("button");
   oBtn.onclick = function() {
      //1. Create an asynchronous object
      var xmlhttp;
      if(window.XMLHttpRequest){
         xmlhttp=new XMLHttpRequest();
      }else{
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// Compatible with IE5 and ie6
      }
      //2. Set the request mode and address
      /* method: request type GET or POST RL: file location on the server async:true or false AJAX meaning asynchronous, so only true */
      xmlhttp.open("GET"."03-AJAX_1.php".true);
      //3. Send request
      xmlhttp.send();
      //4. Listen for state changes
      xmlhttp.onreadystatechange=function(){
         /* Four symbols for status changes 0: request uninitialized 1: server connection established 2: request received 3: request processing 4: request completed and response ready */
         /*HTTP status code 200<= status code <300 or status code ==304 is successful */
         f(xmlhttp.readyState == 4){
            // Indicates whether the request was successful
            if(xmlhttp.status>=200&&xmlhttp.status<300||xmlhttp.status==304) {//5. Process the returned result
               console.log(xmlhttp.responseText);
            }
            else{
               console.log("No data received from server"); }}}; }; }Copy the code

Compatibility in IE

// The XMLHttpRequest object is not supported in IE
var xmlhttp;
if(window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// Compatible with IE5 and ie6
}
// In GET requests, IE treats the same URL as a return result,
// Do not change the url as the server content changes
    // Date (recommended)
xmlhttp.open("GET"."03-AJAX_1.php? t="+ (new Date).getTime(),true);
    / / random number
xmlhttp.open("GET"."03-AJAX_1.php? t="+Math.random(),true);
Copy the code

Encapsulation AJAX

//myAjax.js
function objToStr(obj){
   Key =value&key=value... format
   var res=[];
   obj.time=(new Date).getTime();
   for(var key in obj){
      // Convert the Chinese characters in the URL to the format required by the URL
      // use the encodeURIComponent method
      // The URL can contain only letters, digits, underscores, and ASCII characters
      res.push(encodeURIComponent(key) +"="+ encodeURIComponent(obj[key]));
   }
   return res.join("&");
}
//type: request type "get" or "post"
//url: PHP file path
//data: The information sent to the server is encapsulated as an object
//timeout: request timeout time (milliseconds)
//success: The callback function executes if the request succeeds
//error: the callback function is executed if the request fails
function ajax(option){
   //0. Convert an object to a string
   //1. Create an asynchronous object
   var xmlhttp;
   var str=objToStr(option.data);
   var timer;
   if(window.XMLHttpRequest){
      xmlhttp=new XMLHttpRequest();
   }
   else{
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// Compatible with IE5 and ie6
   }
   //2. Set the request mode and address

   //method: Request type GET or POST
   //url: the file's location on the server
   //async:true or false
   // The meaning of AJAX is asynchronous, so only true

   if(option.type.toLowerCase()=="get"){
      xmlhttp.open("GET",option.url+"?"+str,true);
      //3. Send request
      xmlhttp.send();
   }
   else if(option.type.toLowerCase()=="post"){
      xmlhttp.open("POST",option.url,true);
      // Note: the following code must be placed between open and send
      xmlhttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded")
      //3. Send request
      xmlhttp.send(str);
   }
   //4. Listen for state changes
   xmlhttp.onreadystatechange=function(){
      /* Four symbols for status changes 0: request uninitialized 1: server connection established 2: request received 3: request processing 4: request completed and response ready */
      /*HTTP status code 200<= status code <300 or status code ==304 is successful */
      if(xmlhttp.readyState == 4) {// The request completes the cleanup abort
         clearInterval(timer);
         // Indicates whether the request was successful
         if(xmlhttp.status>=200&&xmlhttp.status<300||xmlhttp.status==304) {//5. Process the returned result
            option.success(xmlhttp);
         }
         else{ option.error(xmlhttp); }}};// Set timeout abort
   if(option.timeout){
      timer=setInterval(function(){
         console.log("Interrupt request");
         xmlhttp.abort();
         clearInterval(timer); },option.timeout); }}Copy the code

In the jQuery AJAX

$.ajax({
   type:"get".url:"03-AJAX_1.php".data:"name=wc&face=noenemy".success:function(x){
      console.log(x);
      console.log("Request successful");
   },
   error:function(){
      console.log("Request failed"); }});Copy the code

Data returned via AJAX is typically XML and JSON (small, common)

XML

<! -- fileNmae: Info.xml -->

      
<! --XML must start with -->
<person>  <! --XML root arbitrary name -->
<name>Eva</name>  <! --XML content named arbitrarily -->
<age>19</age>
</person>
Copy the code
Before retrieving XML from a PHP file, you need the following code to prevent garbled characters
header("content-type:text/xml; charset=utf-8");
// Print the contents of the XML document
// When used in JS, accessed via the asynchronous object.responsexml
// Get the element by the tag name
echo file_get_contents("info.xml");
Copy the code

JSON

{
   "name":"volcano"."age":"19"
}
Copy the code
// Print to get JSON content
// When used in JS, accessed via the asynchronous object.responseText
Parse (JSON) is converted to object access using methods in the native JS tool class JSON
echo file_get_contents("info.json");
Copy the code