Write your own ajax steps

  Steps to write your own Ajax 

  1. Create an XMLHttpRequest object ( the only browser dependency involves the creation of an XMLHttpRequest object . In IE 5 and 6, the IE-specific ActiveXObject() constructor must be used )

 2. Call open(get/post, url , true)  

The first parameter can take the value get or post;

The second parameter is the path of the request; if the first one is the get url, it can be followed by parameters, and if the post cannot have parameters

                                             xhr.setRequestHeader(name, value);//Set the request header

The third parameter is whether to use asynchronous, and it is absolutely true to use ajax.

3. Register the callback function 

xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4) {// Pay attention to the capitalization of readyState here, the HTTP response has been fully received . ,

           if (xhr.status == 200) { / When the status is 200 it is "OK", when the status is 404 it is "NotFound".
               var res = xhr.responseText ; //Receive the returned effect 
           document.getElementById("showcontext").innerHTML = res; //Assign the returned result

            } 
        } 
}

 4. Send  the xhr.send(null) get method if the post method is used xhr.send("")  parameter name = parameter value

  The document case creation object is as follows

  xmlHttp=null;

if (window.XMLHttpRequest)
  {// code for IE7, Firefox, Opera, etc.
 xmlHttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlHttp!=null)
  {
  xmlHttp.open("GET", "note.xml", false);
  xmlHttp.send(null);
  xmlDoc=xmlHttp.responseText;

  xmlHttp.open("POST", "demo_dom_http.asp", false);
  xmlHttp.send(xmlDoc);
  document.write(xmlHttp.responseText);
  }

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326311704&siteId=291194637