Jquery is a good encapsulation of JavaScript, and it is very lightweight. It can be called as a framework in a similar way. Next we will compare the implementation of Ajax by JavaScript and jquery, in order to highlight jquery's encapsulation, it is easy to implement. Besides, using jquery instead of JavaScript to implement some functions will bring unexpected benefits to browser compatibility;
First, it is a simple page:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
The page end defines a click event onclick = "verify ()"; that is, click the button to call the event Method verify ();
Here we first use JavaScript to implement the entire Ajax
// User verification method // This method uses the XMLHTTPRequest object for asynchronous Ajax interaction var XMLHTTP; // sets the global variable so that the callback function can also use its function verify () {// 1. DOM method to get the Value Method in the text box // document. getelementbyid ("username") is a method for Dom to get element nodes. An element node corresponds to a tag on the HTML page, for example, <input> // value can be used to obtain the value attribute value var username = document of an element node. getelementbyid ("username "). value // 2. create an XMLHTTPRequest object // This is the most complex step in using the XMLHTTPRequest object // you need to write different codes if (window. XMLHttpRequest) {// for F Irefox mozillor opera safari, IE7, IE8 XMLHTTP = new XMLHttpRequest (); // fix the bug in the browser of javasillor of certain versions if (XMLHTTP. overridemimetype) {XMLHTTP. overridemimetype ("text/XML") ;}} else if (window. activexobject) {// For IE6 ie5.5 ie5 // two control names that can be used to create an XMLHTTPRequest object, saved in a JS array // the previous version is newer than VaR activexname = ["msxml2.xmlhttp", "Microsoft. XMLHTTP "]; for (VAR I = 0; I <activexname. length; I ++) {try {// retrieve a creation name for creation. Terminate the loop if it succeeds. // if the creation fails, an exception is thrown. You can continue the loop and try to connect XMLHTTP = new activexobject (activexname [I]); break;} catch (e) {}}// confirm that XMLHttpRequest is successfully created if (! XMLHTTP) {alert ("XMLHttpRequest creation failed! "); Return;} else {alert (XMLHTTP. readystate);} // 2. when registering a callback function // when registering a function, you only need the function name and do not need to add brackets. // We need to register the function name. If brackets are added, the function return value will be registered, this is the error XMLHTTP. onreadystatechange = callback; // 3. set the connection information // The first parameter indicates the HTTP request method. It supports all HTTP request methods, mainly get and post. // The second parameter indicates the request URL address, and the GET request parameters are also in the URL. // The third parameter indicates synchronous or asynchronous, and true indicates asynchronous XMLHTTP. open ("get", "ajaxserver? Name = "+ username, true);/* POST request XMLHTTP. open ("Post", "ajaxserver", true); in post mode, you must set the HTTP Request Header XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded") XMLHTTP. send ("name" + username); * // 4. send information, and the server interacts with each other // in synchronous mode. The send statement is executed only after the server data is returned // in asynchronous mode, the XMLHTTP. send (null);} function callback () {alert (XMLHTTP. readystate); // test the status of the readystate at different times, // determine whether the object state is interactive completion if (XMLHTTP. readystate = 4) {// determine whether HTTP interaction is successful if (XMLHTTP. status = 200) {// do not write the two if conditions together, because the readystate starts with a process of 0, 1, 2, and 3. At this time, the callback function is called, this does not meet the judgment conditions. // obtain the data returned by the server // obtain the plain text data output by the server var responsetext = XMLHTTP. responsetext; // display the data on the page // find the node var divnode = Document of the element corresponding to the DIV label in Dom mode. getelementbyid ("result"); // sets the HTML content divnode in the element node. innerhtml = responsetext ;}}}
The Code already contains detailed comments. I will not explain them here;
The following code is implemented using jquery:
// Define the User Name Correction Method function verify () {// first test the button on the page and press it to call this method // use the alert method in Javascript, display a pop-up prompt box // alert ("the button is pressed"); test whether the content in the text box has been obtained in JS // 1 // document. getelementbyid ("username") Dom acquisition method // jquery node search method, # Add ID parameter value in the parameter to find a node // jquery method returns jquery objects, you can continue to execute other jquery methods above var jqueryobj = $ ("# username") // obtain the node value var username = jqueryobj. val (); // alert (username); test whether username is obtained. // 2. send text box data to the server servlet // use jqu The GET request encapsulation of the XMLHTTPRequest object of ery $. Get ("ajaxserver? Name = "+ username, null, callback);} // callback function. Data is the data returned by the server. Function callback (data) {// alert ("server-side data back"); test interaction with server-side // 3. accept the data returned by the server // alert (data); Test Data // 4. dynamically display the data returned by the server on the page // find the node that saves the data var resultobj =$ ("# result "); // dynamically change the DIV content in the page. resultobj.html (data );}
We can see that it is implemented using jquery. After commenting out, there will be less than 10 lines of code. It can be seen that jquey has helped us with a lot of basic work.
To show the entire process, I now implement the background operation class ajaxserver. java. I will not use the framework for simplicity, but use servlet for implementation directly:
Package COM. xidian. ajax; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. servletexception; import Java. io. ioexception; import Java. io. printwriter; import java.net. urldecoder; public class ajaxserver extends httpservlet {protected void doget (httpservletrequest, httpservletresponse htT Pservletresponse) throws servletexception, ioexception {try {httpservletresponse. setcontenttype ("text/html; charset = UTF-8"); printwriter out = httpservletresponse. getwriter (); integer inte = (integer) httpservletrequest. getsession (). getattribute ("Total"); // used to test the cache. in IE, if the address of multiple requests is the same, the request will not read data from the server, instead, it directly reads the cached int temp = 0; If (inte = NULL) {temp = 1;} else {temp = inte. intvalue () + 1;} httpservletrequest. getsess Ion (). setattribute ("Total", temp); // 1. take the string old = httpservletrequest parameter. getparameter ("name"); // string name = new string (old. getbytes ("iso8859-1"), "UTF-8"); // process Chinese garbled 1, with the front-end JS file in the encodeuri with string name = urldecoder. decode (old, "UTF-8"); // process Chinese Garbled text 2 // 2. check whether the parameter is correct. If (old = NULL | old. length () = 0) {out. println ("the user name cannot be blank! ");} Else {// string name = old; // 3. verification operation if (name. equals ("123") {// 4. unlike traditional applications, this step returns data of interest to the page end. Instead of returning a new page to the page, the writing method has not changed, and the essence has changed out. println ("username [" + name + "] already exists. Please use another username !, "+ Temp);} else {out. println (" username ["+ name +"] does not exist. You can use this username !, "+ Temp) ;}} catch (exception e) {e. printstacktrace () ;}} protected void dopost (httpservletrequest, httpservletresponse) throws servletexception, ioexception {doget (httpservletrequest, httpservletresponse );}}
As you can see in the above Code, the processing of cache is very rare in our time application. Here, I just wrote the above Code to solve this problem, we generally do not want a browser
To read the cache, all of us will add a parameter timestamp to the address of the Ajax request in order to cheat the browser, so as to ensure that the addresses of each request are different;
Specific use you can see: http://www.cnblogs.com/shenliang123/archive/2012/04/19/2456758.html
There are two ways of interaction based on AJAX: http://www.cnblogs.com/shenliang123/archive/2012/04/19/2456800.html
Here we implement HTML-based interaction;