Sun's "Ajax and Java EE" full text translation of the basic knowledge

Source: Internet
Author: User
Tags object model xslt
Joking, original source: http://java.sun.com/developer/technicalArticles/J2EE/AJAX/


In English and Chinese as follows, all are my own translation, the level is limited (6 grade test 78 points), welcome correction:





Asynchronous JavaScript Technology and XML (AJAX)


With Java 2 Platform, Enterprise Edition


--"Asynchronous Javascript+xml technology and Java EE"


by Greg Murray, June 9, 2005





  anyone   who   has   used   flickr,    GMail,   Google   Suggest,   or    Google   Maps   will   realize   that    a   new   breed   of   dynamic    web   applications   is   emerging.    these   applications   look   and   act    very   similar   to   traditional    Desktop   applications   without   relying   on    plug-ins   or   browser-specific   features.    Web   applications   have   traditionally   been    a   set   of   HTML   pages    that   must   be   reloaded   to    change   any   portion   of   the    content.   Technologies   such   as    javascript   programming   language   and    cascading   style   sheets    (CSS)    have    matured   to   the   point   where    they   can   be   used    Effectively   to  &nBsp;create   very   dynamic   web   applications    that   will   work   on   all    of   the   major   browsers.    this   article   will   detail   several    techniques   that   you   can   use    today   to   enable   your   web    applications   to   be   more    rich   and   interactive   like   desktop    applications.   --who have used Flickr, GMail, Google, suggest or Google Maps know that a new Dynamic Web application is taking shape, These applications look very similar to traditional desktop applications, they do not rely on plug-ins orBrowser effects. The traditional Web application is a group of web pages, when there is any change in the content of the page must update the entire page. Some technologies such as JavaScript and CSS are already very mature, and you can use them to create dynamic Web pages efficiently and run in most mainstream browsers. This article will detail several techniques that make your Web application richer and more interactive (just like desktop applications).    





Introducing asynchronous JavaScript Technology and XML (AJAX)


--ajax Introduction





  Using   JavaScript   technology,   an    html   page   can   asynchronously   make    calls   to   the   server   from    which   it   was   loaded   and    fetch   XML   documents.   The    XML   documents   may   then   be    used   by   the   JavaScript    technology   to   update   or   modify    the   Document   Object   Model    (DOM)    of   the   html   page.   the   term    Asynchronous   javascript   technology   and   xml     (AJAX)    has   emerged   recently    to   describe   this   interaction   model.    --using JavaScript technology, HTML Web pages can asynchronously invoke the services on the server that generated it and can get the results of the returned XML document form. JavaScript uses this XML document to update or change the Document Object Model (DOM) of this web page, and noun Ajax is the new term that has emerged in recent years to describe this interactive pattern.    





  AJAX   is   not   new.   These    techniques   have   been   available    to   developers   targeting   Internet    explorer   on   the   windows   platform    for   many   years.   until   recently ,   the   technology   was   known    as   web   remoting   or   remote    scripting.   Web   developers   have    also   used   a   combination   of    plug-ins,   java   applets,   and   hidden   frames    to   emulate   this   interaction   model    for   some   time.   what   has    changed   recently   is   that    the   inclusion   of   support   for    the   XMLHttpRequest   object   has    became   ubiquitous   in   the   mainstream    browsers   across   all   platforms.    The   real   magic   is   the    result   of   the   JavaScript   technologys    xmlhttprequest   object.   although   this    object   is   not   specified   in    the   formal   JavaScript   technology    Specification,   all   of   todays   mainstream    browsers   support   it.   The    subtle   differences   with   the    Javascript   technology   and   css   support    among   current   generation   browsers    such   as   firefox,   internet   explorer,   and   safari    are   manageable.   if   you   are    required   to   support   older    browsers,   AJAX   may   not   be    the   answer   for   you.   -- Ajax is not new, and developers who used Microsoft's Internet Explorer a few years ago used it, until recently, when the technology was dubbed a remote script. Previous Web developers used Plug-ins, applets, or hidden frameworks to emulate this interaction pattern. But now that the XMLHttpRequest object technology is already popular in the mainstream browsers of all major platforms, this kind of imitation is becoming less and fewer. The real magic is the combination of JavaScript and XMLHttpRequest object technology, although XMLHttpRequest object technology does not belong to JavaScript standards, but modern mainstream browsers support, in Firefox, IE,    safari These browsers have a slight difference in the execution of JavaScript and CSS, but these differences are easy to understand and handle. If you must be compatible with the older generation of browsers, then do not use Ajax.    


//////////////////////////////////////////////////////////////////////////////////////////








1 floor





BS Lou Pig











2 floor





what   makes   ajax-based   clients   unique    is   that   the   client   contains    page-specific   control   logic   embedded    as   JavaScript   technology.   The    page   interacts   with   the   javascript    technology   based   on   events    such   as   the   document   being    loaded,   a   mouse   click,   focus    changes,   or   even   a   timer .   ajax   interactions   allow   for   a   clear    separation   of   presentation   logic    from   the   data.   An   HTML    page   can   pull   in   bite-size    pieces   of   data   as   needed    rather   than   reloading   the    whole   page   every   time   a    change   needs   to   be   displayed.    ajax   will   require   a   different    server-side   architecture   to   support   this    interaction   model.   traditionally,   server-side    web   applications   have   focused    on   generating   html   documents   for    every   client   event   resulting    in   a   call   to   the    server.   the   clients   would   then    refresh   and   re-render   the   complete    HTML   page   for   each    Response.   rich   web   applications   focus   on    a   client   fetching   an   HTML    document   that   acts   as   a    template   or   container   into    which   to   inject   content,   based    on   client   events   using   XML    data   retrieved   from   a    server-side   component.--What makes an AJAX-based client so unique? That is the page-specific control logic that the client embeds, and the control logic exists in the form of JavaScript code. The interaction between the page and JavaScript is based on events (such as document loading events, mouse click events, focus change events, or even a clock event). Ajax clearly separates the presentation logic from the data, and an HTML Web page can capture bits of data when needed! This differs from the previous practice of having to refresh the entire page with a little change. And Ajax also needs a completelyThe same server-side architecture to support this interaction pattern. Previous traditional server-side Web applications focused on generating HTML pages for each request for each client, and each time the client received a response to refresh and render the entire page. The Web application we're talking about is focused on the fact that the client is using the HTML document as a template or container, and the client inserts content into the container, so that every time a client event occurs, the client can make a request to the server and use the XML data returned by the server.    





Some uses for AJAX interactions are the following:


Real-time Form data validation:form data such as user IDs, serial numbers, postal codes, or Even special coupon codes that require Server-side validation can is validated in a form befo Re the user submits a form.


Autocompletion:a specific portion of form data such as a email address, name, or city name May is autocompleted as the user types.


Master Details operations:based on a client event, an HTML page can fetch more detailed inf   Ormation on data such as a product listing which enables the client to view the individual Product information without refreshing the page.


Sophisticated User Interface controls:controls such as tree Controls, menus, and progress bars May is provided that does not require page refreshes.


Refreshing data on the page:html pages could poll data from a-server for up-to-date data su CH as scores, stock quotes, weather, or application-specific data.


Some examples of Ajax use are as follows:


Real-time form data validation: form data such as ID number, serial number, ZIP code, coupon number can be validated before the user submits the entire form!


Auto-completion: Some specific form data such as email, name, city name can be automatically filled according to the type of user.


Detail action: Based on client-side events, customers can view details of a product without refreshing the page.


Smart Client interface control: such as trees, menus, and toolbars can be serviced at any time without refreshing the page.


Refresh Live Data: Pages can filter dynamic data from the server and display, such as: scores, stock quotes, weather forecasts, and so on.





This list isn't all-inclusive, but it shows that AJAX interactions allow Web applications to   Do much more than they have did in the past. Although many of benefits are noteworthy, this approach has some drawbacks as:


  Complexity:   Server-side   developers   will    need   to   understand   that    presentation   logic   will   be   required    in   the   HTML   client   pages    as   well   as   in   the    server-side   logic   to   generate   the    XML   content   needed   by    the   client   html   pages.   html    page   developers   must   have   javascript    technology   skills.   Creating   AJAX-enabled    applications   will   become   easier   as    new   frameworks   are   created   and    existing   frameworks   evolve   to    support   the   interaction   model.      


Standardization of the XMLHttpRequest object:the XMLHttpRequest Object is not yet part of the JavaScript technology specification, which means that behavior could vary on the CL Ient.


JavaScript Technology Implementations:ajax interactions depend heavily on JavaScript Technology, whic   H has subtle differences depending on the client. Quirksmode.org for more details on browser-specific differences.


Debugging:ajax applications are also difficult to debug because the processing logic is Embedde D both in the client and on the server.


Viewable source:the client-side JavaScript technology May is viewed simply by selecting View so   Urce from a ajax-enabled HTML page. A poorly designed ajax-based application could open itself up to hackers or plagiarism.


  Frameworks   and   patterns   for    ajax   technology   are   likely   to    emerge   as   developers   gain   more    experience   writing   applications   that    use   the   ajax   interaction   model .    it   is   still   early   to    focus   on   a   one-size-fits-all    framework   for   AJAX   interactions.    this   article   and   the   associated    solutions &nbSp; focus   on   how   ajax   interactions    can   be   supported   today    by   existing   java   2   platform,    Enterprise   Edition    (Java ee)    technologies    such   as   servlets,   javaserver   pages     (JSP)    software,   JavaServer   Faces    applications,   and   the   Java    standard   tag   libraries    (JSTL) .      


These are not all useful, but they illustrate the Ajax interaction that makes Web applications do a lot of things that could not be done before. These things may not be so compelling, and there are some flaws:


Complexity: Server-side developers must master XML, page developers must master JavaScript technology.


Standardization of XMLHttpRequest objects: The XMLHttpRequest object is still not a JavaScript standard specification.


JavaScript technology implementations: Ajax relies heavily on JavaScript technology. Refer to quirksmode.org.


Debugging:ajax difficult to debug.


View the original file: Use this method can easily see JavaScript source code, to hackers, plagiarism to exploit.


Ajax technology frameworks and patterns are still too early to explore and experience the formative stages of solidification to form a real framework. This article only explores how to use the Java EE technology to support Ajax interactions.





The anatomy of an AJAX interaction


Now, we have discussed what AJAX are and what some higher-level issues, are put a ll the pieces together and show a ajax-enabled Java EE application.


  lets   consider   an   example.   a    web   application   contains   a    static   HTML   page,   or   an    HTML   page   generated   in   JSP    technology   contains   an   HTML    form   that   requires   server-side   logic    to   validate   form   data   without    refreshing   the   page.   A    server-side   web   component    (servlet)    named    validateservlet   will   provide   the   validation    logic.   figure   1   describes   the    details   of   the   AJAX    interaction   that   will   provide   the    validation   logic   


--ajax Interactive profiling: Look at an AJAX enabled Java EE application: A servlet named Validateservlet validates the form data, but requires that it not refresh the entire page. The steps are as follows:





1, A client event occurs. --The client event occurs.


2, an XMLHttpRequest object is created and configured. --A XMLHttpRequest object is created and configured.


3, the XMLHttpRequest object makes a call. The--xmlhttprequest object makes a request.


4, the request is processed by the Validateservlet. --The request is validateservlet processed.


5, the Validateservlet returns an XML document containing the result. --validateservlet returns an XML document that contains the results.


6, the XMLHttpRequest object calls the callback () function and processes the result. The--xmlhttprequest object invokes the callback () function and processes the result.


7, the HTML DOM is updated.--html Document object is updated.











3 floor





The details of each step are as follows:


1. A Client Event occurs.--incident occurred:


Click the keyboard event for a link or form element to raise the JavaScript function validate ():


<input type= "Text"


Size= "20"


Id= "UserID"


Name= "id"


onkeyup= "Validate ();" >





2. A XMLHttpRequest object is created and configured.--a XMLHttpRequest object was created and configured:


var req;


function Validate () {


var IDfield = document.getElementById ("IDfield");


var url = "validate?id=" + Escape (idfield.value);


if (window. XMLHttpRequest) {


req = new XMLHttpRequest ();


else if (window. ActiveXObject) {


req = new ActiveXObject ("Microsoft.XMLHTTP");--Create XMLHttpRequest Object


}


Req.open ("Get", url, True);--The open method that invokes the XMLHttpRequest object, the URL is the requested server-side component path, and True indicates that the call is asynchronous,





If set to asynchronous, you must also have a callback function as follows:


Req.onreadystatechange = callback;


Req.send (NULL);


}





3. The XMLHttpRequest object makes a Call.--xmlhttprequest objects issue a request:


A request is made when executing to req.send (null).





If it is a GET request, then the content can be empty, with the parameters appended to the URL.


If it is a POST request, then a content-type header is required to set the following:


Req.setrequestheader ("Content-type", "application/x-www-form-urlencoded");


Req.send ("id=" + Escape (idtextfield.value));





If you produce a form element value in JavaScript, you must ensure that the value is encoded correctly, and JavaScript has an escape () function that protects the correct encoding and ignores the specific characters correctly.





4. The request is processed by the validateservlet.--requests are processed by the Validateservlet:


The servlet handles XMLHttpRequest just as it does with other HTTP requests:





public class Validateservlet extends HttpServlet {


Private ServletContext context;


Private HASHMAP users = new HashMap ();


public void init (ServletConfig config) throws servletexception {


This.context = Config.getservletcontext ();


Users.put ("Greg", "account Data");


Users.put ("Duke", "account Data");


}


public void doget (HttpServletRequest request, httpservletresponse response)


Throws IOException, Servletexception {





String Targetid = request.getparameter ("id");





if ((Targetid!= null) &&!users.containskey (Targetid.trim ())) {


Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("valid");


} else {


Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("invalid");


}


}


}





5. The Validateservlet returns an XML document containing the Results.--validateservlet returns an XML file containing the results.


Validateservlet generates an XML document as a response, and more complex situations can be used in DOM, XSLT, and so on.





Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("invalid");





Developers must understand two things: first: Content-type must be set to Text/xml; second: Cache-control must be set to No-cache.











4 floor





Up











5 Floor





6. The XMLHttpRequest object calls the callback () function and processes the result.


The--xmlhttprequest object invokes the callback () function and processes the result.





  The   XMLHttpRequest   object   was    Configured   to   call   the   callback ()     function   when   there   are    changes   to   the   readystate   of    the   xmlhttprequest   object.   let   us    assume   the   call   to   the    ValidateServlet   was   made   and    the   readystate   is   4,   signifying    the   XMLHttpRequest   call   is    complete.   the   http   status   code   of   200    signifies   a   successful   HTTP    interaction.     


When the preparation state of the--xmlhttprequest object changes, the callback () method is invoked, we assume that the request has been completed Validateservlet, the preparation status is 4, the XMLHttpRequest call has been completed, The HTTP status code is 200, indicating that the HTTP interaction has been successful.





function callback () {


if (req.readystate = = 4) {


if (Req.status = = 200) {


Update the HTML DOM based on whether or isn't message is valid


}


}


}





  Browsers   maintain   an   object    Representation   of   the   documents   being    displayed    (referred   to   as    the   Document   Object   Model   or    dom) .   javascript   technology   in    an   HTML   page   has   access    to   the   DOM,   and   APIs    are   available   that   allow   javascript    technology   to   modify   the    dom   after   the   page   has   loaded.      


--The browser maintains a document's object representation model, both: DOM. The JavaScript method in the Web page can access the model, and it can be changed again after the page has been fully loaded.





  Following   a   successful   request,    JavaScript   technology   code   may    modify   the   dom   of   the    html   page.   the   object   representation    of   the   XML   document   that    was   retrieved   from   the    Validateservlet   is   available   to   javascript    technology   code   using   the    req.responsexml,   where   req   is   an    xmlhttprequest    object.   the   dom   apis   provide    a   means   for   JavaScript    technology   to   navigate   the   content    from   that   document   and   use    that   content   to   modify    The   dom   of   the   html   page.    The   string   representation   of    the   XML   document   that   was    returned   may   be   accessed   by    calling   req.responsetext.   now   lets   look    at   how   to   use   the    dom   apis   in   javascript   technology    by   looking   at   the   following    XML   document   returned   from    the   ValidateServlet.     


--Use JavaScript code: Req.responsexml can get the XML document returned by the server, req as XMLHttpRequest object, DOM provides JavaScript with a means to search for document content and to change the DOM of a Web page based on search results. You can use Req.responsetext to access the string representation of the returned XML document, as shown here:





<message>


Valid


</message>





  This   example   is   a   simple    xml   fragment   that   contains   the    sender   of   the   message    element,   which   is   simply   the    string   valid   or   invalid.   A    more   advanced   sample   may    contain   more   than   one   message    and   valid   names   that   might    be   presented   to   the   user:      


--The example above is a simple XML fragment, the actual application may contain more:





function Parsemessage () {


var message = Req.responseXML.getElementsByTagName ("message") [0];


Setmessage (Message.childnodes[0].nodevalue);


}





The Parsemessages () function would process an XML document retrieved from the Validateservlet.    This function would call the Setmessage () with the value of the "message element" to update the HTML DOM.


The--parsemessages () method handles the XML document returned from the server, and the method uses the value of the message element to invoke the Setmessage () method to alter the HTML DOM.











6 floor





Good Admire... Thank you Landlord











7 Floor





Not bad! Very good translation! Landlord English is very good ah! It's 6 levels ..... Xi hee ...











8 Floor





7. The HTML DOM is updated.--html Document object is updated.





  JavaScript   technology   can   gain    a   reference   to   any   element    in   the   HTML   DOM   using    a   number   of   APIs.   The    recommended   way   to   gain   a    reference   to   an   element    Is   to   call   document.getelementbyid ("UserIdMessage"),    where    "Useridmessage"    is   the    id   attribute   of   an   element    appearing   in&Nbsp;  the   html   document.   with   a    reference   to   the   element,    javascript   technology   may   now   be    used   to   modify   the    Elements   attributes;   modify   the   elements    style   properties;   or   add,    remove,   or   modify   child   elements.      


One common means to change the body content of a element is to set the InnerHTML property On the element as in the following example.


--javascript can obtain a reference to any element (object) in the HTML DOM, and the recommended use of the document.getElementById ("Useridmessage") method. Useridmessage is the id attribute of any element on a Web page, a reference to an element (object), JavaScript can change the attributes of the element and the style attribute of the element, and can also increase the deletion or change of the element's child elements. The common approach is to set the innerHTML property, as shown below:





<script type= "Text/javascript" >


function setmessage (message) {


var usermessageelement = document.getElementById ("Useridmessage");


usermessageelement.innerhtml = "<font color=\" red\ ">" + message + "</font>";


}


</script>


<body>


<div id= "Useridmessage" ></div>


</body>





  The   portions   of   the   HTML    page   that   were   affected   are    re-rendered   immediately   following   the    setting   of   the   innerHTML.    if   the   innerhtml   property   contains    elements   such   as   <image>    or   <iframe>,   the   content    specified   by   those   elements   is    fetched   and   rendered   as   well.    


When the--innerhtml property is changed, the Web page can immediately change, and if the innerHTML attribute contains elements such as <image>, <iframe>, then the resource content specified by the browser is parsed and displayed.





  the   main   drawback   with   this    approach   is   that   HTML    elements   are   hardcoded   as   strings    in   the   JavaScript   technology    code.   hardcoding   html   markup   inside    JavaScript   technology   code   is    not   a   good   practice   because    it   makes   the   code   difficult    to   read,   maintain,   and   modify.    consider   using   the   JavaScript   technology    DOM   APIs   to   create   or    modify   HTML   elements   within    javascript   technology   code.   intermixing    presentation   with   javascript   technology    code   as   strings   will   make    a   page   difficult   to   read    and   edit.   


Another means of modifying the HTML DOM is to dynamically create new elements and append the M as children to a target element as in the following example.


The biggest drawback of this approach is that it's hard to read, maintain, and change HTML in a JavaScript code that is hard to write in a string, embedded in JavaScript. Another way to change the HTML DOM is to dynamically create a new element and then insert it as a child element under the target element, as shown below:





<script type= "Text/javascript" >


function setmessage (message) {


var usermessageelement = document.getElementById ("Useridmessage");


var Useridmessagefont = document.getElementById ("Useridmessagefont");


var messageelement = document.createtextnode (message);


if (Usermessageelement.childnodes[0]) {


Update the Elements


Useridmessagefont.replacechild (Messageelement, useridmessagefont.childnodes[0]);


} else {


Create the new elements


var fontelement = document.createtextnode ("Font");


Fontelement.setatribute ("id", "Useridmessagefont");


Fontelement.setatribute ("Color", "red");


Usermessageelement.appendchild (fontelement);


Fontelement.appendchild (messageelement);


}


}


</script>


<body>


<div id= "Useridmessage" ></div>


</body>





--The full text, exhausted.











9 Floor





Compact version:





The page-specific control logic that the client embeds is in the form of JavaScript code. The interaction between the page and JavaScript is based on events (such as document loading events, mouse click events, focus change events, or even a clock event). Ajax clearly separates the presentation logic from the data, and an HTML Web page can capture bits of data when needed! This differs from the previous practice of having to refresh the entire page with a little change. Ajax also requires a completely different server-side architecture to support this interaction pattern. Previous traditional server-side Web applications focused on generating HTML pages for each request for each client, and each time the client received a response to refresh and render the entire page. The Web application we're talking about is focused on the client's use of HTML documents as templates or containers, and the client inserts content into them, and the principle is that every time a client occurs, the client can make a request to the server and consume the XML data returned by the server.





The servlet named Validateservlet validates the form data, but requires that the entire page not be refreshed. The steps are as follows:





1. A Client Event occurs.--incident occurred:


Click the keyboard event for a link or form element to raise the JavaScript function validate ():


<input type= "Text"


Size= "20"


Id= "UserID"


Name= "id"


onkeyup= "Validate ();" >





2. A XMLHttpRequest object is created and configured.--a XMLHttpRequest object was created and configured:


var req;


function Validate () {


var IDfield = document.getElementById ("IDfield");


var url = "validate?id=" + Escape (idfield.value);


if (window. XMLHttpRequest) {


req = new XMLHttpRequest ();


else if (window. ActiveXObject) {


req = new ActiveXObject ("Microsoft.XMLHTTP");--Create XMLHttpRequest Object


}


Req.open ("Get", url, True);--The open method that invokes the XMLHttpRequest object, the URL is the requested server-side component path, and True indicates that the call is asynchronous,





If set to asynchronous, you must also have a callback function as follows:


Req.onreadystatechange = callback;


Req.send (NULL);


}





3. The XMLHttpRequest object makes a Call.--xmlhttprequest objects issue a request:





If it is a GET request, then the content can be empty, with the parameters appended to the URL.


If it is a POST request, then a content-type header is required to set the following:


Req.setrequestheader ("Content-type", "application/x-www-form-urlencoded");


Req.send ("id=" + Escape (idtextfield.value));





If you produce a form element value in JavaScript, you must ensure that the value is encoded correctly, and JavaScript has an escape () function that protects the correct encoding and ignores the specific characters correctly.





4. The request is processed by the validateservlet.--requests are processed by the Validateservlet:


The servlet handles XMLHttpRequest just as it does with other HTTP requests:





public class Validateservlet extends HttpServlet {


Private ServletContext context;


Private HASHMAP users = new HashMap ();


public void init (ServletConfig config) throws servletexception {


This.context = Config.getservletcontext ();


Users.put ("Greg", "account Data");


Users.put ("Duke", "account Data");


}


public void doget (HttpServletRequest request, httpservletresponse response)


Throws IOException, Servletexception {





String Targetid = request.getparameter ("id");





if ((Targetid!= null) &&!users.containskey (Targetid.trim ())) {


Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("valid");


} else {


Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("invalid");


}


}


}





5. The Validateservlet returns an XML document containing the Results.--validateservlet returns an XML file containing the results.


Validateservlet generates an XML document as a response, and more complex situations can be used in DOM, XSLT, and so on.





Response.setcontenttype ("Text/xml");


Response.setheader ("Cache-control", "No-cache");


Response.getwriter (). Write ("invalid");


Developers must understand two things: first: Content-type must be set to Text/xml; second: Cache-control must be set to No-cache.





6. The XMLHttpRequest object calls the callback () function and processes the result.


The--xmlhttprequest object invokes the callback () function and processes the result.


When the preparation state of the XMLHttpRequest object changes, the callback () method is invoked, we assume that the request has been completed Validateservlet, the preparation status is 4, the XMLHttpRequest call has been completed, The HTTP status code is 200, indicating that the HTTP interaction has been successful.





function callback () {


if (req.readystate = = 4) {


if (Req.status = = 200) {


Update the HTML DOM based on whether or isn't message is valid


}


}


}


The browser maintains a document's object representation model, both: DOM. The JavaScript method in the Web page can access the model, and it can be changed again after the page has been fully loaded.





Using JavaScript code: Req.responsexml can get the XML documents returned by the server, req for XMLHttpRequest objects, DOM provides JavaScript with a way to search for document content, and to change the DOM of Web pages based on search results. You can use Req.responsetext to access the string representation of the returned XML document, as shown here:





<message>


Valid


</message>





The example above is a simple XML fragment, and the actual application may contain more:





function Parsemessage () {


var message = Req.responseXML.getElementsByTagName ("message") [0];


Setmessage (Message.childnodes[0].nodevalue);


}





The Parsemessages () method handles the XML document returned from the server, and the method uses the value of the message element to invoke the Setmessage () method to alter the HTML DOM.





7. The HTML DOM is updated.--html Document object is updated.





JavaScript can get a reference to any element (object) in the HTML DOM, and it is recommended to use the document.getElementById ("Useridmessage") method to get it. Useridmessage is the id attribute of any element on a Web page, a reference to an element (object), JavaScript can change the attributes of the element and the style attribute of the element, and can also increase the deletion or change of the element's child elements. The common approach is to set the innerHTML property, as shown below:





<script type= "Text/javascript" >


function setmessage (message) {


var usermessageelement = document.getElementById ("Useridmessage");


usermessageelement.innerhtml = "<font color=\" red\ ">" + message + "</font>";


}


</script>


<body>


<div id= "Useridmessage" ></div>


</body>





When the innerHTML property is changed, the Web page can immediately change, and if the innerHTML attribute contains elements such as <image>, <iframe>, then the resource content specified by the browser is parsed and displayed.





The biggest drawback of this approach is that it's hard to read, maintain, and change HTML in a JavaScript code that is hard to write in a string, embedded in JavaScript. Another way to change the HTML DOM is to dynamically create a new element and then insert it as a child element under the target element, as shown below:





<script type= "Text/javascript" >


function setmessage (message) {


var usermessageelement = document.getElementById ("Useridmessage");


var Useridmessagefont = document.getElementById ("Useridmessagefont");


var messageelement = document.createtextnode (message);


if (Usermessageelement.childnodes[0]) {


Update the Elements


Useridmessagefont.replacechild (Messageelement, useridmessagefont.childnodes[0]);


} else {


Create the new elements


var fontelement = document.createtextnode ("Font");


Fontelement.setatribute ("id", "Useridmessagefont");


Fontelement.setatribute ("Color", "red");


Usermessageelement.appendchild (fontelement);


Fontelement.appendchild (messageelement);


}


}


</script>


<body>


<div id= "Useridmessage" ></div>


</body>
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.