Two Ajax interaction Methods: HTML and XML

Source: Internet
Author: User

Compare jquery's implementation of these two interactions:

HTML-based interaction:

Function verify () {// method 1 to solve the Chinese Garbled text problem. The data sent by the page is used as an encodeuri, and the server uses new string (old. getbytes ("iso8859-1"), "UTF-8") // var url = "ajaxserver? Name = "+ encodeuri ($ (" # username "). val (); // encodeuri handles Chinese Garbled text; // method 2 to solve Chinese Garbled text. the data sent by the page is processed by encodeuri twice, and the server uses urldecoder. decode (old, "UTF-8"); var url = "ajaxserver? Name = "+ encodeuri ($ (" # username "). val (); // encodeuri for handling Chinese garbled characters url = converturl (URL); // obtain the function return value 'login? Uname = '+ uname +' & psw = '+ psw $. get (URL, null, function (data) {$ ("# result" ).html (data); // simplified version}); system. out. println (URL);} // Add a timestamp to the URL. the browser is cheated and the function converturl (URL) is not read from the cache) {// obtain the timestamp var timstamp = (new date ()). valueof (); // splice the timestamp information to the URL if (URL. indexof ("? ")> = 0) {// use indexof to determine whether the URL address has a question mark (url = URL +" & t = "+ timstamp;} else {url = URL + "? T = "+ timstamp;} return URL ;}

Background page:

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 );}}

The above implementation is commonly used based on HTML, but relatively simple;

Below we implement XML-based interaction: JS:

// 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 the data in the text box to the servlet // JavaScript on the server, and define a simple object // var OBJ = {name: "123", age: 30} // use the GET request encapsulation of the XMLHTTPRequest object of jquery $. ajax ({type: "Post", // HTTP request URL: "ajaxxmlserver", // server URL data: "name =" + username, // datatype of the data sent to the server: "XML", // inform the server of the returned data type success: callback // defines that the interaction is complete, and the callback function called when the server correctly returns data})} // 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 // You Need to parse the data in the data DOM object // first you need to convert the DOM object to the jquery object var jqueryobj = $ (data ); // obtain the message node var messsage = jqueryobj. children (); // obtain the text content var text = message. text (); // The returned values of all subnodes are obtained here, because the message returns an array. // 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 );}

Background code:

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; public class ajaxxmlserver extends httpservlet {protected void doget (httpservletrequest, httpservletresponse) throws Servletexception, ioexception {try {// modify point 1 ---- the response Content-Type must be text/XML, which is very important to httpservletresponse. setcontenttype ("text/XML; charset = UTF-8"); printwriter out = httpservletresponse. getwriter (); // 1. take the string old = httpservletrequest parameter. getparameter ("name"); // 2. check whether the parameters are correct // modify point 2 ---- the returned data needs to be encapsulated into the XML format stringbuilder builder = new stringbuilder (); builder. append ("<message>"); // The returned content of XML must be included in <message> </message> If (old = NULL | old. Length () = 0) {// whether the content of the text box to be verified is null builder. append ("the user name cannot be blank! "). Append ("</message>");} 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 builder has changed in essence. append ("user name [" + name + "] already exists. Please use another user name! "). Append (" </message> "); // out. println (" username ["+ name +"] already exists. Please use another username! ");} Else {// out. println (" username ["+ name +"] does not exist. You can use this username! "); Builder. append (" user name ["+ name +"] does not exist. You can use this user name! "). Append ("</message>");} Out. println (builder. tostring (); // This is a required system. out. println ("output content:" + Builder. tostring (); // press the tab key after entering sout to generate a catch (exception e) {e. printstacktrace () ;}} protected void dopost (httpservletrequest, httpservletresponse) throws servletexception, ioexception {doget (httpservletrequest, httpservletresponse );}}

I have already marked all vertices of the two methods. You can compare them and use the method that you can accept;

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.