Native way to achieve ajax

  • AJAX is asynchronous JavaScript and XML. It is a technology that can update part of the web page without reloading the entire web page.
  • If you need to update the content of a traditional web page (not using AJAX), you must reload the entire web page.
  • There are many application cases that use AJAX: Sina Weibo, Google Maps, Kaixin, etc.

Steps to implement Ajax using native methods:

1. Create an XMLHttpRequest object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.
Insert picture description here
Old versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
Insert picture description here
2. Send a request to the server
Insert picture description here
(1) Send a get request

xmlhttp.open(“GET”,“test1.txt”,true);

If you want to send information via the GET method, please add information to the URL:
Insert picture description here

(2) Send post request

If you need to POST data like an HTML form, use setRequestHeader() to add HTTP headers. Then specify the data you want to send in the send() method:
Insert picture description here
3. The server responds

To get the response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
Insert picture description here
(1) responseText

The responseText property returns the response in the form of a string, which can be used like this: Insert picture description here
(2) responseXML

If the response from the server is XML and needs to be parsed as an XML object, please use the responseXML attribute:
Insert picture description here
4. Determine whether the response is successful.
Insert picture description here
When the readyState is equal to 4 and the status is 200, the response is ready: Insert picture description here
5. A complete Ajax request

var xmlhttp;
if (window.XMLHttpRequest) {
    
    // code for IE7+, Firefox, Chrome, Opera, Safari
  	xmlhttp=new XMLHttpRequest();
}
else {
    
    // code for IE6, IE5
  	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
  
xmlhttp.open("GET","请求url",true);

xmlhttp.onreadystatechange=function(){
    
    
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    
    
  		//响应成功要做的事
  		document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.send();

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/114657030