Home > Article > Web Front-end > How to implement AJAX request?
How to implement AJAX request?
1. Create an XMLHttpRequest instance;
var xhr;if(window.XMLHttpRequest) { //ie7+,firefox,chrome,safari,opera xhr = new XMLHttpRequest();}else { //ie5,ie6 xhr = new ActiveXObject("Microsoft.XMLHTTP");}
2. Listen to the readystatechange event and determine the request status through the readyState attribute;
xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { console.log(xhr.responseText); }}
3. Call open() The method specifies the request type and address;
xhr.open("GET", "xhr_info.txt");
4. Just call the send() method to send the request.
xhr.send(null);
Complete code
var xhr; if(window.XMLHttpRequest) { //ie7+,firefox,chrome,safari,opera xhr = new XMLHttpRequest(); } else { //ie5,ie6 xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { console.log(xhr.responseText); } } xhr.open("GET", "xhr_info.txt", true); xhr.send(null);
Recommended tutorial: "JS Tutorial"
The above is the detailed content of How to implement AJAX request?. For more information, please follow other related articles on the PHP Chinese website!