Passing Data Using XML

Source: Internet
Author: User

Servlet

 PackageOrg.zln.ajax.servlet;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;ImportJava.io.PrintWriter;/*** Created by Coolkid on 2015/6/7 0007.*/ Public classAjaxserverextendsHttpServlet {@Overrideprotected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request,response); } @Overrideprotected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try{            /*using XML processing*/Response.setcontenttype ("Text/xml;charset=utf-8"); Request.setcharacterencoding ("UTF-8"); PrintWriter out=Response.getwriter (); //Take parameter informationString name = Request.getparameter ("name"); //Input ChecksumStringBuilder StringBuilder =NewStringBuilder (); Stringbuilder.append ("<message>"); if(Name = =NULL|| Name.length () = = 0) {stringbuilder.append ("User name cannot be empty"). Append ("</message>"); } Else{                //logical check and business processing                if(Name.equals ("Wangxingkui") {stringbuilder.append ("User name [" + name + "] already exists, please use a different user name"). Append ("</message>"); } Else{stringbuilder.append ("User name [" + name + "] does not exist and can be registered with this user name"). Append ("</message>");            } out.println (Stringbuilder.tostring ()); }            /*The data sent to the HTML will be processed by the Ajax callback function*/Out.println ("<br/><a href=\" ajax.html\ "> Return to Validation page </a>"); } Catch(Exception e) {e.printstacktrace (); }        //returns update data (instead of jumping to a new view)    }}

Js

/** * Created by Coolkid on 2015/6/7 0007.*/varXmlHttp =NULL;functionverifynew (ID) {/*get the data you want to plan*/    varUsername =document.getElementById (ID). value; /*Create a XMLHttpRequest object*/    if(window. XMLHttpRequest) {/*for Firefox mozillar Opera Safair ie7+*/xmlHttp=NewXMLHttpRequest (); /*bug fixes for some versions of the Mozillar browser*/        if(Xmlhttp.overridemimetype) {Xmlhttp.overridemimetype (' Text/xml '); }    } Else if(window. ActiveXObject) {/*for IE6 IE5.5 IE5*/        varActivexname = [            ' MSXML2. XMLHTTP ',            ' Microsoft.XMLHTTP '        ];  for(vari = 0; i < activexname.length; i++) {            Try {                /*take out a space name to create and terminate the loop if the creation succeeds*/xmlHttp=NewActiveXObject (Activexname[i]);  Break; } Catch(e) {} }}if(!xmlHttp) {Alert (' XMLHttpRequest object creation failed '); } Else {        /*Registering callback Functions*/Xmlhttp.onreadystatechange=callback; /*set connection True to indicate asynchronous interaction*/Xmlhttp.open (' GET ', '/lesson5_ajax_demo1/ajaxservletdo.do?name= ' + username,true); /*If you use post, you need to set the request header yourself*/        /*Xmlhttp.open ("POST", "/lesson5_ajax_demo1/ajaxservletdo.do" +username,true);        Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");        Xmlhttp.send ("name=" +username); */        /*Send Data*/Xmlhttp.send (NULL);/*because the data sent is already in the URL, the send data parameter here is set to null*/    }}functioncallback () {if(Xmlhttp.readystate = = 4) {/*Interactive Completion*/        //determine if the HTTP interaction is successful        if(Xmlhttp.status = = 200) {            //use Responsexml to receive the DOM object of an XML data Object            varDomobj =Xmlhttp.responsexml; if(domobj) {//<message>123123123</message>                //The DOM uses getElementsByTagName to get the element node based on the tag name, returning an array                varMessagenodes = domobj.getelementsbytagname (' message ')); if(Messagenodes.length > 0) {                    //gets the text content in the message node                    //The text in the message label is the byte point of the element node corresponding to the message label in the DOM, and FirstChild can get to the first child node of the current node                    //you can get the node that corresponds to the text content in the following ways                    varTextnode = Messagenodes[0].firstchild; //for text nodes, you can return text content of a text node in a nodevalue way                    varResponsemessage =Textnode.nodevalue; //displaying Data on a page                    //find the element node corresponding to the DIV tag in the DOM way                    varDivnode = document.getElementById (' result '); //to set HTML content in an element nodedivnode.innerhtml =Responsemessage; } Else{alert (' XML data format error, original text content is: ' +xmlhttp.responsetext); }            } Else{alert (' XML data format error, original text content is: ' +xmlhttp.responsetext); }        } Else{alert (' Wrong!!! ‘); }    }}

Passing Data Using XML

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.