What can Ajax do?
Now Google Suggest and Google Maps use Ajax. Through Ajax, we can make the client get rich application experience and exchange operations, without the user feeling that there is a Web page submission or refresh process, the page does not need to be reloaded, and the data exchange of the application is hidden.
The traditional WEB application model works like this: User Interface operations trigger HTTP requests, and the server processes some business logic after receiving the requests, such as saving data, then return an HTML page to the client. However, this method does not give users a good application experience. When the server is processing data, the user is in the waiting state, and each step of operation needs to wait, too much waiting will make users less and less patient. Ajax is very different. It uses the Ajax engine to make the application process natural and smooth, because it only exchanges useful data with the server, the page display and other unnecessary data are not reloaded. The Ajax engine is actually a comprehensive application of JavaScript, XML, XMLHttpRequest, and other technologies.
Why AJAX?
1. Better User experience through appropriate Ajax applications;
2. Transfer the previous server workload to the client, which facilitates the idle processing capability of the client to reduce the burden on the server and bandwidth, this saves ISP space and bandwidth rental costs.
Where does AJAX come from?
Jesse James Garnett, the earliest author of the Ajax concept, believes that:
Ajax is short for Asynchronous JavaScript and XML.
Ajax is not a new language or technology. It is actually a combination of several technologies in a certain way to play their respective roles in the same collaboration, including:
- Use XHTML and CSS for standardized rendering;
- Use DOM for Dynamic Display and interaction;
- Use XML and XSLT for data exchange and processing;
- Use XMLHttpRequest for asynchronous data reading;
- Finally, use JavaScript to bind and process all data;
The working principle of Ajax is equivalent to adding an intermediate layer between the user and the server, so that user operations and server responses are asynchronous. Not all user requests are submitted to the server, for example, some data verification and data processing are handed over to the Ajax engine, the Ajax engine submits requests to the server only when it is determined that new data needs to be read from the server.
What are the core AJAX technologies?
Although Garrent lists seven Ajax components, I personally think that the core of the so-called Ajax is JavaScript, XMLHTTPRequest, and DOM. If the data format is XML, you can also add XML (the data returned by Ajax from the server can be in XML format or other formats such as text ).
In the old interaction mode, the user triggers an HTTP request to the server. After the server processes the request, it returns a new HTHL page to the client, each time the server processes a request submitted by the client, the client can only wait idle, and even if it is only a small interaction, it only needs to get a simple data from the server, you must return a complete HTML page, and each time you have to waste time and bandwidth to re-read the entire page.
After Ajax is used, users feel that almost all operations will quickly respond to the waiting without page overloading (white screen.
XMLHttpRequest (XmlHttp)
It is an API that can be transmitted over http or received from XML and other data in Javascript, VbScript, Jscript, and other scripting languages. XmlHttp can be used to update part of the webpage without refreshing the entire page.
Explanation from MSDN: XmlHttp provides the protocol for communication between the client and the http server. The client can send a request to the http server through the XmlHttp Object (MSXML2.XMLHTTP. 3.0) and process the response using the Microsoft XML Document Object Model (DOM.
Currently, most browsers have added support for XmlHttp. in IE, XmlHttp objects are created using ActiveXObject. other browsers, such as Firefox and Opera, use window. XMLHttpRequest to create xmlhttp objects.
Attribute:
Onreadystatechange * |
Specifies the event processing handle when the readyState attribute changes. Write only |
ReadyState |
Returns the status of the current request, read-only. |
ResponseBody |
Returns the response body in the unsigned byte array. Read-Only |
ResponseStream |
Return the response information in the form of an Ado Stream object. Read-Only |
ResponseText |
Returns the response information as a string. Read-Only |
ResponseXML |
Format the response information as an Xml Document Object and return it. Read-Only |
Status |
Returns the http status code of the current request. Read-Only |
StatusText |
Returns the response line status of the current request, read-only |
This section focuses on readyState attributes.
Returns the current status of the XMLHTTP request. Each value represents a status.
0 (not initialized) |
Object created but not initialized (open method not called) |
1 (initialization) |
The object has been created and the send method has not been called |
2 (send data) |
The send method has been called, but the current status and http header are unknown. |
3 (data transmission in progress) |
Some data has been received. Because the response and http headers are incomplete, an error occurs when you obtain some data through responseBody and responseText, |
4 (finished) |
After receiving the data, you can use responseBody and responseText to obtain the complete response data. |
Method:
Abort |
Cancel current request |
GetAllResponseHeaders |
Get all http headers of the response |
GetResponseHeader |
Obtain the specified http header from the response information |
Open |
Create a new http request and specify the request method, URL, and authentication information (User Name/password) |
Send |
Send a request to the http server and receive a response |
SetRequestHeader |
Specify an http header of the Request separately |
How can I use Ajax correctly?
Here, we will use the case that user registration verification is frequently used in a project to check whether duplicate user names exist. Return json in get mode, json in post mode, and xml in post mode.
First, we need to consider how to obtain XmlHttp objects in different browsers.
Function creatXmlHttpRequest () {if (typeof XMLHttpRequest! = 'Undefined') {return new XMLHttpRequest ();} else if (typeof ActiveXObject! = 'Undefined') {var MSXML = ['msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; for (var I = 0; MSXML. length; I ++) {try {return new ActiveXObject (version [I]);} catch (e ){//.......}}} else {throw new Error ('your system or browser does not support XHR objects! ');}}
Return json in GET Mode
Function checkUserByAjaxGet () {// step 1, get an XMLHttpRequest object // var xhr = new XMLHttpRequest (); // if you say IE6, you need to use Active to form // xmlhttp = new ActiveXObject (MSXML [n]); var xhr = creatXmlHttpRequest (); var name = document. rgform. username. value; // sets the event listening function xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 304) {var ret = xhr. responseText; var _ ret = eval ('+ ret + '); // Var _ ret = JSON. parse (ret); document. getElementById ("msg "). innerHTML = _ ret. tip; if (_ ret. success = true) {document. rgform. username. focus () ;}}}// step 2, prepare a connection request for xhr. open ("get", "checkuserByJSON. jsp? Name = "+ name, true); // step 3, initiate the request xhr. send (null );}
Return json in POST Mode
Function checkUserByAjaxPost () {// Step 1: Create the xhr object var xhr = creatXmlHttpRequest (); var name = document. rgform. username. value; // step 2, set the event listening function xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 304) {var ret = xhr. responseText; var _ ret = eval ('+ ret +'); // var _ ret = JSON. parse (ret); document. getElementById ("msg "). innerHTML = _ ret. tip; if (_ ret. success = true) {document. rgform. username. focus (); alert (xhr. getResponseHeader ("Content-Length"); alert (xhr. getResponseHeader ("Content-Type"); alert (xhr. getResponseHeader ("Date"); alert (xhr. getResponseHeader ("Server") ;}}// step 3, prepare a POST Connection Request for xhr. open ("post", "checkuserByJSON. jsp ", true); // use the post method for submission. The following xhr line must be added. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); // Step 4: Initiate the xhr request. send ("name =" + name + "& password = ppppp ");}
POST-return xml
Function checkUserByAjaxPostXml () {// Step 1: Create the xhr object var xhr = creatXmlHttpRequest (); var name = document. rgform. username. value; // step 2, set the event listening function xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 304) {var ret = xhr. responseXML; var successNode = ret. getElementsByTagName ("success") [0]; var tipNode = ret. getElementsByTagName ("tip") [0]; document. getElementById ("msg "). innerHTML = tipNode. firstChild. nodeValue; if (successNode. firstChild. nodeValue = true) {document. rgform. username. focus () ;}}}// Step 3: Prepare a POST Connection Request for xhr. open ("post", "checkuserByXML. jsp ", true); xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); // Step 4: Initiate the xhr request. send ("name =" + name + "& password = ppppp ");}
Returned json
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <% @ page import = "java. util. * "%> <% String username = request. getParameter ("username"); response. setContentType ("application/json; charset = UTF-8"); response. setHeader ("pragma", "no-cache"); response. setHeader ("cache-control", "no-cache"); if ("admin ". equals (username) {response. getWriter (). write ("{\" success \ ":" + true + ", \" tip \ ": \" username already exists \ "}");} else {response. getWriter (). write ("{\" success \ ":" + false + ", \" tip \ ": \" username can be \ "}") ;}%>
Returned xml
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <% @ page import = "java. util. * "%> <% String userId = request. getParameter ("name"); response. setContentType ("application/xml; charset = UTF-8"); response. setHeader ("pragma", "no-cache"); response. setHeader ("cache-control", "no-cache"); if ("admin ". equals (userId) {response. getWriter (). write ("<root> <success> true </success> <tip> the user name already exists </tip> </root>");} else {response. getWriter (). write ("<root> <success> false </success> <tip> User Name available </tip> </root>") ;}%>
Interface
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
If you have used jQuery asynchronous request methods, you must think that method is quite easy to use. In comparison, the method described above is quite tedious, the get method and the post method even have some code, which are quite different. How can we block these differences through code? Here we copy jQuery's $. ajax () method.
// Encapsulate ajaxfunction ajax (obj) {var xhr = creatXmlHttpRequest (); obj. url = obj. url + '? Rand = '+ Math. random (); obj. data = params (obj. data); if (obj. method = 'get') obj. url + = obj. url. indexOf ('? ') =-1? '? '+ Obj. data: '&' + obj. data; if (obj. async === true) {xhr. onreadystatechange = function () {if (xhr. readyState = 4) {callback () ;};} xhr. open (obj. method, obj. url, obj. async); if (obj. method = 'post') {xhr. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); xhr. send (obj. data);} else {xhr. send (null);} if (obj. async === false) {callback ();} function callback () {if (xhr. status = 200) {Obj. success (xhr. responseText); // callback transfer parameter} else {alert ('data Acquisition Error! Error code: '+ xhr. status +', error message: '+ xhr. statusText );}}}
// Function params (data) {var arr = []; for (var I in data) {arr. push (encodeURIComponent (I) + '=' + encodeURIComponent (data [I]);} return arr. join ('&');}
Call our encapsulated ajax Method
window.onload = function(){document.getElementById("username").onchange = function(){ajax({method : 'post',url : 'checkuserByJSON.jsp',data : {'username' : document.rgform.username.value,'password' : document.rgform.password.value},success : function (text) {var _ret = eval('(' + text + ')'); document.getElementById("msg").innerHTML = _ret.tip;},async : true});}}
What we pass to ajax is an object. Is it very close to jQuery.