- 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.
Old versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
2. Send a request to the server
(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:
(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:
3. The server responds
To get the response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
(1) responseText
The responseText property returns the response in the form of a string, which can be used like this:
(2) responseXML
If the response from the server is XML and needs to be parsed as an XML object, please use the responseXML attribute:
4. Determine whether the response is successful.
When the readyState is equal to 4 and the status is 200, the response is ready:
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();