Ajax is the abbreviation of asynchronous JavaScript and XML, and is a mechanism to update a certain part of the page. It gives you the power to update a part of the page after you get data from the server, thus avoiding refreshing the entire page. In addition, realizing local page updates in this way can not only effectively create a smooth user experience, but also reduce the load on the server.
Here is an analysis of a basic Ajax request:
var xhr = new XMLHttpRequest();xhr.open('GET', 'send-ajax-data.php');xhr.send(null);Here, we create an instance of a class that can make HTTP requests to the server. Its open method is then called, where the first parameter is the HTTP request method and the second parameter is the URL of the request page. Finally, we call the send method with the parameter null. If you use the POST request method (we use GET here), the send method parameters should contain any data you want to send.
Here is how we handle the server's response:
xhr.onreadystatechange = function(){ var DONE = 4; // readyState 4 means that the request has been sent to the server var OK = 200; // status 200 means that the server returns successfully if(xhr.readyState === DONE){ if(xhr.status === OK){ console.log(xhr.responseText); // This is the returned text} else{ console.log("Error: "+ xhr.status); // Error occurred in this request} }}onreadystatechange is asynchronous, so that means it will be called at any time. This type of function is called a callback function - once some processing is completed, it is called. In this case, this processing occurs on the server.
Example
The convenient Ajax method is also the reason why many people rely on jQuery, but in fact, the Ajax API of native JavaScript is also very powerful, and the basic usage is not much different in each browser. Therefore, you can completely encapsulate an Ajax object by yourself. The following is the encapsulated Ajax object:
// Ajax method// Lazy load create xhr object function createXHR(){ if ( 'XMLHttpRequest' in window ){ createXHR = function(){ return new XMLHttpRequest(); }; } else if( 'ActiveXObject' in window ){ createXHR = function(){ return new ActiveXObject("Msxml2.XMLHTTP"); }; } else { createXHR = function(){ throw new Error("Ajax is not supported by this browser"); }; } return createXHR(); } // Ajax executes function request(ajaxData){ var xhr = createXHR(); ajaxData.before && ajaxData.before(); // Handle asynchronous requests through events xhr.onreadystatechange = function(){ if( xhr.readyState == 4 ){ if( xhr.status == 200 ){ if( ajaxData.dataType == 'json' ){ // Get the json object returned by the server jsonStr = xhr.responseText; json1 = eval('(' + jsonStr + ')'), json2 = (new Function('return ' + jsonStr))(); ajaxData.callback(json2); // ajaxData.callback(JSON.parse(xhr.responseText)); // Native method, not supported in IE6/7} else ajaxData.callback(xhr.responseText); } else { ajaxData.error && ajaxData.error(xhr.responseText); } } }; // Set request parameters xhr.open(ajaxData.type, ajaxData.url); if( ajaxData.noCache == true ) xhr.setRequestHeader('If-Modified-Since', '0'); if( ajaxData.data ){ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send( ajaxData.data ); } else {? ? xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send( null ); } return xhr;} function post(ajaxData){ ajaxData.type = 'POST'; var _result = request(ajaxData); return _result;} function get(ajaxData){ ajaxData.type = 'GET'; ajaxData.data = null; var _result = request(ajaxData); return _result;}Here is an example of usage:
index.html
<!DOCTYPE HTML><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>Native JavaScript Implementation Ajax</title> <link rel="stylesheet" type="text/css" media="all" href="./common/common.css" /> <style> #content {text-align: center; font-family: 'lucida Grande', 'Microsoft Yahei'} #content .btn_ctr {display: block; width: 120px; height: 30px; margin: 0 auto 20px; background: #53a7bb; color: #fff; font-weight: bold; font-size: 14px; line-height: 30px; text-decoration: none; border-radius: 4px; } #test {width: 280px; height: 130px; margin: 0 auto; padding: 15px; background: #fff; border-radius: 4px; text-align: left; } </style></head><body> <div id="header"> <div id="header-content"> <div id="header-inside"> <p><a href="http://kayosite.com/css3-animation.html" target="_blank" >Back To Article</a></p> <p><a href="http://kayosite.com" target="_blank" >My Blog</a></p> <p>Demo By Kayo © Copyright 2011-2013</p> </div> <h1>CSS3 Animation</h1> </div> </div> <div id="content"> <a href="javascript:;" onclick="get({url: './ajax.html', callback: function(out){document.getElementById('test').innerHTML = out;}})">Ajax Get content</a> <div id="test"></div> </div> <script> // Ajax method, not listed repeatedly here</script></body></html> ajax.html<!DOCTYPE HTML><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>ajax</title></head><body> <p>Successfully obtained this text</p></body></html>
For specific effects, you can browse the full demo.