Ajax and how it works
AJAX is a technology that exchanges data with servers without refreshing web pages. It was first used by Google in Google Maps and was quickly popular.
AJAX cannot be cross-domain. If you need to cross-domain, you can use document.domain='a.com'; or use a server proxy to proxy XMLHttpRequest file.
AJAX is based on existing Internet standards and uses them in combination:
XMLHttpRequest object (asynchronously exchanges data with the server)
JavaScript/DOM (Information display/interaction)
CSS (Define styles for data)
XML (as the format for converting data)
Create XMLHttpRequest object
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.
Create an Ajax object:
//IE6 or above
var oAjax = new XMLHttpRequest();
//IE6
var oAjax =new ActiveXObject("Microsoft.XMLHTTP")
Connect to the server
oAjax.open(method, url, is it asynchronous)
We all know that Ajax, namely "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), refers to a web development technology that creates interactive web applications. Therefore, Ajax is born to work in asynchronous mode (asynchronous is true, synchronous false)
Synchronous and asynchronous
Synchronization refers to the communication method in which the sender sends data and waits for the receiver to send a response before sending the next data packet.
Asynchronous refers to the communication method in which the sender sends data without waiting for the receiver to send a response and then sends the next data packet.
(To put it simply: synchronization can only be done one thing one by one, while asynchronous can be done multiple things at the same time)
Send request send()
The code copy is as follows:
<script type="text/javascript">
function getDoc(){
var xmlhttp;
if(window.xmlhttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//for IE6
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("myId").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", index.php,true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="getDoc()">Request data</button>
</body>
GET or POST?
Compared to POST, GET is simpler and faster and is available in most cases.
However, use the POST request in the following cases:
Unable to use cached files (update files or databases on the server)
Send large amounts of data to the server (POST has no data limit)
POST is more stable and reliable than GET when sending user input containing unknown characters
Receive return information
oAjax.onreadystatechange = function(){ // Event handler to be called when the request state changes
alert(oAjax.readystate);
}
Whenever the value of the readyState property changes, a readyStatechange event will be triggered. This event can be used to detect the value of readyState after each state change. Usually, we are only interested in the stage where the readyState value is 4, because all the data is ready at this time, however, the onreadystatechange event handler must be specified before calling open() to ensure cross-browser compatibility. Let’s take a look at an example:
The code copy is as follows:
var xhr = createXHR();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.statusText);
} else {
alert("Request was unsuccessful: " + xhr.status);
}
}
};
xhr.open("get", "example.txt", true);
xhr.send(null);
XHR Objects
When an XHR object sends an HTTP request to the server, it goes through several states until the request is processed, and then receives a response. readyState is the state property of the XHR request, which itself has 5 property values:
0 (uninitialized) The open() method has not been called yet
1 (Load) The send() method has been called and the request is being sent
2 (Loading is completed) The send() method has been completed and all response content has been received
3 (Analysis) Response content is being parsed
4 (Complete) The response content parsing is completed and can be used by the client.
status
The status attribute represents the response status code returned from the server. For example: 200 means success, 404 means not found.
1-word header: message. This type of status code means that the request has been accepted and needs to be processed.
2-word head: Success. This type of status code means that the request has been successfully received, understood and accepted by the server.
3-word header: redirection. This type of status code means that further actions are required by the client to complete the request.
4-character header: Client error. This type of status code means that the client may appear to have an error, which hinders the server's processing.
5-word header: Server error. This type of status code represents an error or abnormal state occurred during the server's request processing process
Also attached: Detailed explanation of http status code
statusText
statusText is the text information returned in the response and can only be used if the readyState value is 3 or 4. When readyState is another value, the view accesses the statusText property will throw an exception.
XHR method
| method | describe |
|---|---|
| abort() | Causes the currently executing request to be cancelled |
| getAllResponseHeaders() | Returns a single character|string containing the names and values of all response headers |
| getResponseHeader(name) | Returns the name and value specified in the response header |
| open(method,url,async,username,pwd) | Set HTTP methods (get or post) etc. |
| send(content) | Issue a request with the specified subject content |
| setRequestHeader(name,value) | Set request header with specified name and value |
The code copy is as follows:
<script type="text/javascript">
var oAjax =oAjax();
alert(oAjax.readyState);//"0" pops up"
oAjax.open("get","index.html",true);
alert(oAjax.readyState);//"1" pops up
oAjax.send(null);
alert(oAjax.readyState);// 4 pops up under IE, while firefox is 2
//You can listen through the readystatechange event
oAjax = XHR();
oAjax.onreadystatechange = function () {
alert(oAjax.readyState);//The order under Firefox is 1, 2, 3, 4, but in the end, there will be another 1
//Under IE it is 1, 1, 3, 4
};
oAjax.open("get","index.txt",true);
oAjax.send(null);
</script>