AJAX learning notes
1 what is AJAX?
AJAX = asynchronous JavaScript and XML
AJAX is a technology for creating fast dynamic web pages.
A small amount of data can be exchanged asynchronously with the AJAX server in the background. You can update a part of a web page without reloading the whole web page. Traditional web pages (without AJAX) must reload the whole web page if they need to update the content.
2 how Ajax works
AJAX is based on the existing Internet standards
AJAX is based on existing Internet standards and uses them together:
- XMLHttpRequest object (asynchronously exchanging data with the server)
- JavaScript/DOM (information display / interaction)
- CSS (define styles for data)
- XML (as a format for transforming data)
4 AJAX - create XMLHttpRequest object
In order to cope with all modern browsers, including IE5 and IE6, please check whether the browser supports XMLHttpRequest object. If supported, create an XMLHttpRequest object. If not, create ActiveXObject:
var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
5 AJAX - send request to server
1 send request to server
To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object:
xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send();
2. The difference between get and POST
Compared with POST, GET is simpler and faster, and can be used in most cases.
However, use POST requests when:
- Cannot use cache file (update file or database on server)
- Send a large amount of data to the server (POST has no limit on the amount of data)
- When sending user input containing unknown characters, POST is more stable and reliable than GET
2.1 GET request
// Simple GET request xmlhttp.open("GET","/try/ajax/demo_get.php",true); xmlhttp.send(); // To avoid getting a cache, add a unique ID to the URL: xmlhttp.open("GET","/try/ajax/demo_get.php?t=" + Math.random(),true); xmlhttp.send(); // If you want to send information through the GET method, add information to the URL: xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true); xmlhttp.send();
2.2 POST request
// A simple POST request: xmlhttp.open("POST","/try/ajax/demo_post.php",true); xmlhttp.send(); // If you need POST data like HTML forms, use setRequestHeader() to add HTTP headers. Then specify the data you want to send in the send() method xmlhttp.open("POST","/try/ajax/demo_post2.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");
2.3 difference between get and POST
Standard answer:
- GET is harmless when the browser goes back, and POST will submit the request again.
- The URL address generated by GET can be bookmarked, but POST cannot.
- GET requests will be actively cache d by the browser, but POST will not, unless manually set.
- GET requests can only be url encoded, while POST supports multiple encoding methods.
- The GET request parameters will be completely retained in the browser history, while the parameters in POST will not be retained.
- The parameters transmitted by GET request in URL are limited in length, while POST does not.
- For the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.
- GET is less secure than POST because parameters are directly exposed to the URL and cannot be used to pass sensitive information.
- The GET parameter is passed through the URL, and the POST is placed in the Request body.
What are GET and POST? Two methods of sending requests in HTTP protocol.
What is HTTP? HTTP is a protocol based on TCP/IP about how data communicates in the world wide web.
The bottom layer of HTTP is TCP/IP. Therefore, the bottom layer of GET and POST is also TCP/IP, that is, both GET and POST are TCP links. GET and POST can do the same thing. You need to add request body to GET and url parameter to POST, which is technically feasible.
In our world wide web, TCP is like a car. We use TCP to transport data. It is very reliable and there will never be a loss of parts. But if the road as like as two peas looks like the same car, the world looks chaotic. The rush truck may be blocked by the truck laden with goods ahead, and the whole traffic system will be paralyzed. In order to avoid this situation, traffic rules were born. HTTP sets several service categories for automobile transportation, including GET, POST, PUT, DELETE, etc. HTTP stipulates that when executing the GET request, the automobile should be labeled with GET (set the method to GET), and the transmitted data should be placed on the roof (url) for recording. If it is a POST request, you should affix a POST label on the car and put the goods in the carriage. Of course, you can also hide some goods in the carriage during GET, but it's very disgraceful; You can also put some data on the roof during POST, which makes people feel silly. GET and POST are only the basic principles of TCP implementation.
However, we only see that HTTP requires the transmission channel (url or requrest body) of GET and POST parameters. Where does the limit on parameter size in "standard answer" come from?
There is another important role in our world wide web: transportation companies. Different browsers (initiating http requests) and servers (accepting http requests) are different transportation companies. In theory, though, you can pile unlimited loads on the roof (add unlimited parameters to the url). But transportation companies are not stupid. Loading and unloading also have great costs. They will limit the single transportation volume to control the risk. Too much data is a great burden on browsers and servers. The unwritten rule in the industry is that (most) browsers usually limit the url length to 2K bytes, while (most) servers can handle URLs of up to 64K size. The excess part will not be handled. If you use the GET service and hide data in the request body, the processing methods of different servers are also different. Some servers will unload and read the data for you, and some servers will ignore it directly. Therefore, although GET can bring the request body, it cannot be guaranteed to be received.
Well, now you know, GET and POST are essentially TCP links, and there is no difference. However, due to the provisions of HTTP and the limitations of browser / server, they reflect some differences in the application process.
There is another major difference between GET and POST. To put it simply:
GET generates a TCP packet; POST generates two TCP packets.
Long said:
For the GET request, the browser will send the http header and data together, and the server will respond 200 (return data);
For POST, the browser sends the header first, the server responds to 100 continue, the browser sends data, and the server responds to 200 ok (return data).
Because POST takes two steps and consumes a little more time, it seems that GET is more effective than POST. Therefore, the Yahoo team recommends replacing POST with GET to optimize website performance. But this is a pit! Be careful when jumping in. Why?
- Both GET and POST have their own semantics and cannot be mixed casually.
- According to research, in the case of good network environment, the difference between the time of sending one packet and the time of sending two packets can be ignored. In the case of poor network environment, TCP with two packets has great advantages in verifying the integrity of data packets.
- Not all browsers send packages twice in POST, and Firefox only sends them once.
3 url - file on server
The url parameter of the open() method is the address of the file on the server:
xmlhttp.open("GET","ajax_test.html",true);
The file can be any type of file, such as txt and xml, or server script files, such as asp and php (able to perform tasks on the server before returning a response).
4 asynchronous - True or False
AJAX refers to Asynchronous JavaScript and XML.
If the XMLHttpRequest object is to be used in AJAX, the async parameter of its open() method must be set to true:
xmlhttp.open("GET","ajax_test.html",true);
Through AJAX, JavaScript does not need to wait for the response of the server, but:
- Execute other scripts while waiting for a response from the server
- Process the response when it is ready
4.1 Async=true
When async=true is used, specify the function to execute when the response is in the ready state in the onreadystatechange event
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body>
4.2 Async = false
To use async=false, change the third parameter in the open() method to false:
xmlhttp.open("GET","test1.txt",false);
async=false is not recommended, but it is also possible for some small requests.
Remember that JavaScript will wait until the server response is ready to continue. If the server is busy or slow, the application hangs or stops.
Note: when you use async=false, do not write the onreadystatechange function - just put the code after the send() statement:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","/try/ajax/ajax_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } </script> </head> <body> <div id="myDiv"><h2>use Ajax Modification content</h2></div> <button type="button" onclick="loadXMLDoc()">Modification content</button> </body> </html>
6 AJAX - server response
6.1 server response
To get a response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
6.2 responseText property
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>use AJAX Modify the text content</h2></div> <button type="button" onclick="loadXMLDoc()">Modification content</button> </body> </html>
6.3 responseXML attribute
If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; var txt,x,i; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","cd_catalog.xml",true); xmlhttp.send(); } </script> </head> <body> <h2>My collection CD :</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my CD</button> </body> </html>
7 AJAX - onreadystatechange event
7.1 onreadystatechange event
When the request is sent to the server, we need to perform some response based tasks.
The onreadystatechange event is triggered whenever the readyState changes.
The readyState property holds the status information of XMLHttpRequest.
The XMLHttpRequest object has three important properties:
In the onreadystatechange event, we specify the task to be performed when the server response is ready to be processed.
When readyState equals 4 and the state is 200, the response is ready:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 browser execution code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>use AJAX Modify the text content</h2></div> <button type="button" onclick="loadXMLDoc()">Modification content</button> </body> </html>
Note: the onreadystatechange event is triggered 4 times (0 - 4), which are 0-1, 1-2, 2-3 and 3-4 respectively, corresponding to each change of readyState.
7.2 using callback functions
A callback function is a function that is passed to another function as a parameter.
If there are multiple AJAX tasks on your website, you should write a standard function for creating the XMLHttpRequest object and call it for each AJAX task.
The function call should contain the URL and the task to be performed when the onreadystatechange event occurs (each call may be different):
<!DOCTYPE html> <html> <head> <script> var xmlhttp; function loadXMLDoc(url,cfunc) { if (window.XMLHttpRequest) {// IE7+, Firefox, Chrome, Opera, Safari code xmlhttp=new XMLHttpRequest(); } else {// IE6, IE5 code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction() { loadXMLDoc("/try/ajax/ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>use AJAX Modify text content</h2></div> <button type="button" onclick="myFunction()">Modification content</button> </body> </html>