© 2009 Marty Hall

The Dojo JavaScript Toolkit j p Part I: Ajax Support
( j (Dojo 1.3 Version) ) Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html p j
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 Marty Hall

For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t htt // l t /
Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization.
•C Courses d developed and t l d d taught b M t H ll ht by Marty Hall • Courses developed and taught by coreservlets.com experts (edited by Marty)
– Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on 1EE Training: http://courses.coreservlets.com/ or survey several Customized Java library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure)

Servlets,Hibernate/JPA, EJB3, Ruby/Rails – Spring, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Contact hall@coreservlets.com for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

Topics in This Section
• • • • Overview of Dojo Installation and documentation Quick summary of dojo.query and selectors The dojo.xhrGet function and variants
– – – – – Basics Options O ti Sending data Inserting HTML Handling JSON data

• Comparing Ajax support to other libraries p g j pp
– Prototype, jQuery, Ext-JS

© 2009 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Overview of Dojo
• Core
– Utilities for Ajax, CSS querying, DOM manipulation, cross-browser event handling, and general JavaScript programming – Very similar to jQuery

• Dijit j
– Large set of rich GUI components – Much more extensive than jQuery UI

• D j X DojoX
– Charts, graphs, vector graphics, fancy widgets – Similar to the jQuery Plugins

Core Utilities
• dojo.query("css selector")
– Returns a NodeList of matching DOM elements.
• Almost identical to $("css selector") in jQuery.

• dojo xhrGet({options}) dojo.xhrGet({options})
– Makes an Ajax GET request. Also dojo.xhrPost, etc.
• Moderately similar to $.ajax({options}) in jQuery y j ({ }) j y

– Example
• dojo.xhrGet({ url: "address", load: responseHandler });

• dojo addOnLoad(function) dojo.addOnLoad(function)
– Calls function after DOM loaded.
• Almost identical to $( u ct o ) in jQuery ost de t ca $(function) jQue y

• dojo.require("dojo.libraryName")

– Loads Dojo libraries on the fly

z. 9.zip or dojo-release-x.y.js) is small.6 or later (vs.0 for jQuery) – Dijit: not supported! • Chrome – 1.0 or later (same as jQuery) • Internet Explorer – 6. dijit.gz • This tutorial uses release 1.5 or later (vs 2. 3.gz dojo-release-x.0 or later 10 .zip dojo release x.org/docs 9 Browser Compatibility • Firefox – Core: 1.0 or later (same as jQuery) • Safari – 3.z.0 for jQuery) • Opera – Core: 9.dojotoolkit. creating 3 subfolders: dojo. dojox • Folders are quite large.tar.y.z.require statements.org/ – Choose “Download latest Stable Release”.1 or later (vs. • Other files are loaded on-the-fly based on dojo.y.1 • Installation – Unzip release file.3.z.Downloading and Installation • Download – http://download. then dojo release x. but core file (dojo.tar.y.0 for jQuery) – Dijit: 2. – Copy 3 folders to WebContent/scripts of Eclipse project • Online documentation – http://dojotoolkit.

At public venues or onsite at your location.query dojo query & Selectors: Basics Note: brief intro only. Ajax.Industry Usage 11 Approximately 40% of matches to “prototype and JavaScript” were false positives such as “build a prototype with JavaScript”. So. discount the Prototype graph by about 40%. Struts. Customized Java EE Training: http://courses. Hibernate/JPA. More details in next tutorial section. © 2009 Marty Hall dojo. JSP. GWT. Spring.com/ Servlets. . Java 5 & 6. JSF/MyFaces/Facelets.coreservlets. Developed and taught by well-known author and developer.

Also wipeIn. etc.forEach(f2) . – dojo. fadeIn.NodeList-html").blah") • Return all elements that have class="blah" – dojo.byId("some-id").query("selector").query( selector ).query("css selector") to get a set of DOM elements • Then.query("#some-id") • Return 1-element set (or empty set) of element with id • Simplest use and most common for Ajax (note the “#”!) use.query(".addClass("name"). – dojo.play() • Makes invisible.wipeOut().value • Returns value of input element. Also onchange.onclick(function) • Adds onclick handler. Also removeClass toggleClass each removeClass.query("selector").blah") 13 • Return all <span class="blah"> elements that are inside b elements. – Must use dojo.forEach(function) (" l t ") f E h(f ti ) • Calls function on each element.query("a"). – dojo.Selecting DOM Elements • Idea – Use dojo. fadeOut. • Chaining 14 – dojo.query("li b span. – dojo. etc.onclick(f1). #.query("selector"). “this” set to element. onmouseover. that in turn are inside li elements Manipulating DOM Elements • Common functions on matched elements – d j dojo.query("selector").query("p") • Return all p elements – dojo.byId("some-id") to get single element – dojo.html("<tag>some html</tag>") • Sets the innerHTML of each element element. perform operations on each (see next page) • Examples – dojo.require("dojo. Notice no “#”. – dojo query("selector") onclick(function) dojo.addClass("name") • Adds CSS class name to each. # !) • Can also use dojo.

wipeOut().query(heading). function setRandomStyle(heading) { dojo. Slowly hide every h3 that has CSS style “green”.NodeList-fx"). Explained in next section.query("h3.play(). Sets onclick handlers 15 Example: Randomizing Colors (JavaScript Continued) Call setRandomStyle function on each h3 element function randomizeHeadings() { dojo. The online docs tell you if a certain function necessitates a “dojo require” statement “dojo. “yellow” or “green” CSS names to each 16 .green"). which you then call play on.forEach(setRandomStyle).require” statement. ti The main two needed for basics apps are dojo.NodeList-html. } Note difference from jQuery approach: wipeOut returns an Animation. }).query( h3 ).addClass(randomStyle()).Example: Randomizing Background Colors (JavaScript) dojo. Like smart window. Loads extra JavaScript on the fly.query("#button1").NodeList-fx and dojo.addOnLoad(function() { dojo. dojo.require("dojo.onclick(revertHeadings).query("#button2"). d j (h di ) ddCl ( d St l ()) } Add “red”. dojo.onload.onclick(randomizeHeadings). dojo query("h3") forEach(setRandomStyle). dojo.

dojo.green { background-color: green } … Names set by setRandomStyles function 18 . "green"]. } function revertHeadings() { u ct o e e t ead gs() dojo.play().yellow { background-color: yellow } yellow .removeClass("red") ( y ) . } 17 Example: Randomizing Colors (Style Sheet) .green"). [ red yellow green ]. } function randomElement(array) { var index = Math.random()*array.red { background-color: red } .removeClass("green").length).wipeIn().floor(Math.query("h3"). return(array[index]).removeClass("yellow") .query("h3.Example: Randomizing Colors (JavaScript Continued) function randomStyle() { var styles = ["red". "yellow". return(randomElement(styles)).

js" type="text/javascript"></script> <script src=". The dojo. type="text/css"/> <script src=". Written for example in next chapter. 19 Example: Randomizing Colors (HTML) … <head><title>Dojo Basics</title> <link rel="stylesheet" Core Dojo.require statements.css" cause on-the-fly loading of additional files. To start with./css/styles. JSP pages called by Ajax examples. j q Written for next example in this chapter.js" < i t " / i t /d j b i j " type="text/javascript"></script> </head> 20 ./scripts/dojo-basics.js. Other files brought in via dojo.Example: Eclipse Setup Servlet and auxiliary code called by Ajax examples. Written for this example./scripts/dojo/dojo. you only need to load dojo/dojo. Copied from Dojo download.require statements href=".

yadda</h3> <form action="#"> # <input type="button" id="button1" value="Randomize Headings"/> <input type="button" id="button2" value="Revert Headings"/> </form> … The ids to which onclick handlers were attached. 22 When page originally loaded. blah</h3> <h3>Yadda. or after “Revert Headings” . yadda. bar. <h3>Foo bar baz</h3> <h3>Blah. Some headings turned green. 21 Example: Randomizing Colors (Results) After “Randomize Headings”. yadda</h3> <h3>Foo. yadda.Example: Randomizing Colors (HTML Continued) … <h3>Foo. <h3>Foo bar baz</h3> <h3>Blah. blah</h3> <h3>Yadda. bar. blah</h3> <h3>Yadda. blah. blah. then gradually disappeared. b </h3> baz</h3> <h3>Blah. yadda. b <h3>F bar. yadda</h3> <h3>Foo. blah.

dojo.query("h3"). } 23 © 2009 Marty Hall dojo.query(heading).query("h3. . JSF/MyFaces/Facelets. } • Why can’t I simply do this? function randomizeHeadings() { dojo. Struts.play().query("h3"). d j ("h3") ddCl ( d St l ()) dojo.wipeOut(). dojo query("h3 green") wipeOut() play(). Ajax. Developed and taught by well-known author and developer.xhrGet: Basics Customized Java EE Training: http://courses.addClass(randomStyle()). GWT.com/ Servlets. Hibernate/JPA.query("h3. Java 5 & 6.addClass(randomStyle()). At public venues or onsite at your location.green"). JSP.play().forEach(setRandomStyle). Spring.green"). } y ( g) function setRandomStyle(heading) { dojo.Understanding Operations on Sets of Elements • Instead of this function randomizeHeadings() { dojo.coreservlets.wipeOut().

dojo. }. dojo. "some-url".open("GET".ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")). • Also dojo.xhrGet({…}) j ({ }) – Almost-always used • url.xhrPut. } else { return(null).send(null). error.onreadystatechange = function() { someFunct(request). } 26 . request. handleAs 25 Data-Centric Ajax with and without Toolkits • With basic JavaScript function getRequestObject() { if (window. request.XMLHttpRequest) { return(new XMLHttpRequest()). true).xhrGet: Basic Syntax • dojo. – Handler function gets response text. load – Other common options • content.xhrGet(optionsObject) – Minimal form: dojo.xhrGet({url: "address".xhrPost. Response text is text considered a string unless you use handleAs option.xhrDelete. etc. } else if (window. • Options for dojo. } } function sendRequest() { var request = getRequestObject(). load: funct}). request. preventCache.dojo.

} function showAlert(text) { ( ). but is a convenient option when the same URL (including query data) yields different responses.request({url: "address". This is the response text.Ajax.xhrGet Example Code: JavaScript function showTime1() { dojo. 27 dojo. " load: handlerFunct}). • Ext (handler passed response object) Ext. • Dojo (handler passed response text) dojo. alert(text).jsp". This way. {onSuccess: handlerFunct}).ajax({url: "address". Also note that the latest Firefox does not let you pass native functions here. success: handlerFunct}). • Prototype (handler passed response object) new Ajax. you don’t have to send Cache-Control and Pragma headers from server. success: handlerFunct}).Data-Centric Ajax with and without Toolkits • jQuery (handler passed response text) $. preventCache: true }). but you can declare a second argument (ioArgs) if you want the response object (XmlHttpRequest) and other information.Request("address". so you cannot use alert instead . y of showAlert for the success parameter. 28 . load: showAlert.xhrGet({url: " dd d j h G t({ l "address". } The preventCache option is not required.xhrGet({ dojo xhrGet({ url: "show-time.

..xhrGet Example Code: HTML … <head><title>Dojo and Ajax</title> Ajax</title>./scripts/dojo-ajax..xhrGet: Basics (Using explicit onclick handler in HTML)</legend> ) / <form action="#"> <input type="button" value="Show Time" onclick="showTime1()"/> </form> </fieldset>… 29 dojo.Date() %> 30 .js" src=" /scripts/dojo ajax js" type="text/javascript"></script> </head> <body>.xhrGet Example Code: JSP It is now <%= new java.util./scripts/dojo/dojo.dojo.. <b d > <fieldset> <legend>dojo. <script src=".js" type="text/javascript"></script> <script src=".

Handler is passed a DOMEvent with characteristics that are unified across browsers 32 .onclick(someHandler). but does not wait .addOnLoad(function() {…}).onload • Use this approach to set up all event handlers – dojo query("#some-id") onclick(someHandler).dojo. Although this is common with other Ajax libraries.xhrGet : Results 31 Registering Event Handlers in JavaScript • Basic approach – Previous example set the onclick handler in the HTML. Dojo (and jQuery) advocate setting it in the JavaScript instead • Often referred to as “unobtrusive JavaScript”: no explicit JavaScript anywhere in the HTML page • Dojo support – dojo. • Assigns onclick handler.query( #some id ). for images. • Function runs after the DOM is loaded. as with window. dojo.

addOnLoad(function() { dojo.xhrGet({ url: "show-time.Redoing Time Alert: JavaScript dojo. 33 Redoing Time Alert: HTML <fieldset> <legend>dojo.xhrGet: Basics ( l d d j h G t i (Registering i t i onclick handler in JavaScript)</legend> <form action="#"> <input type="button" value="Show Time" id="time-button-1"/> </form> </f > </fieldset> 34 . }).onclick(showTime1).jsp". load: showAlert. } These two functions are unchanged from previous example. function showTime1() { dojo. preventCache: true }). } function showAlert(text) { alert(text). dojo query("#time button 1") onclick(showTime1).query("#time-button-1").

xhrGet: dojo xhrGet: Sending Data g Customized Java EE Training: http://courses. .Redoing Time Alert: Results Works exactly the same as previous example example. Java 5 & 6. JSP.com/ Servlets. At public venues or onsite at your location. Developed and taught by well-known author and developer. JSF/MyFaces/Facelets. Hibernate/JPA. GWT. 35 © 2009 Marty Hall dojo.coreservlets. Struts. Spring. Ajax.

but lets you provide the raw data for the body of the request 37 Overview • dojo. content: …}). 38 . load: ….xhrDelete – Make a PUT or DELETE request – Unsupported on many servers • dojo. param2: "baz"}}). – Content value is an object: query string gets built out of property names and URL-encoded property values • O end of URL f ajax. dojo. dojo.rawXhrPost.rawXhrPut j .Ajax Functions • dojo.xhrGet({ url: ….xhrGet. On d f for j hG t in POST body for dojo.xhrPost({options}) – M k a POST request Make • dojo. hasBody) – Lets you send arbitrary HTTP commands • dojo. j – Sends a POST or PUT request. j ({ p .xhrPost • See later example for building the string automatically using the “form” option • Works identically to “parameters” option in Prototype or “data” option in jQuery data • Examples – dojo.xhrGet({options}) – Make a GET request • dojo.xhrPut.xhr("method".xhrGet({… content: { param1: "foo bar!". {options}.

function showAlert(text) { alert(text).xhrGet({ Get({ url: "show-params.jsp". load: showAlert }). } Same function used in earlier examples. 39 function showParams1() { dojo. content: { param1: "foo". } The preventCache option is not used since the same data always results in the same response.query( #params button 1 ).onclick(showParams1). p param2: "bar" }. Content Example: HTML … <fieldset> <fi ld t> <legend>dojo.xhrGet: The 'content' Option</legend> <form action="#"> <input type="button" value="Show Params" id="params-button-1"/> </form> </fieldset> … 40 . dojo query("#params-button-1") onclick(showParams1). dojo.Content Example: JavaScript dojo. … }).addOnLoad(function() { dojo.

41 Content Example: Results 42 .Content Example: JSP param1 is ${param.param2}.param1}. param2 is ${param param2} ${param.

param2: "baz"}.xhrPost and others • Common options: example dojo. you might want to just fire off some data to the server and not display anything p y y g • Options apply equally to dojo. Developed and taught by well-known author and developer. . Struts.xhrGet({url: "some-address". JSF/MyFaces/Facelets. content: { param1: "foo bar".coreservlets. error: errorHandlerFunction. JSP. load: successHandlerFunction. Hibernate/JPA. Spring. • load is not strictly required. handleAs: "json" }).com/ Servlets. preventCache: t tC h true. Ajax.xhrGet({ url: "address". load: someFunc}). 44 . At public venues or onsite at your location.xhrGet: Options Customized Java EE Training: http://courses. Overview • Options (almost) always used: url.© 2009 Marty Hall dojo. GWT. Java 5 & 6. load – dojo.

and xhr. th d t b t t th Function to be called if request succeeds. json. More common t use separate load and error properties.preventCache parameter with a timestamp that changes with each request. xml. but most useful are args. M to t l d d ti The format in which to pass the response to the handler function. in the form on an object with param names d to i th f bj t ith and raw (non-escaped) param values. Default Empty E t error None form handle handleAs 45 None None "text" Options (Continued) Name headers h d load Description Extra E t HTTP request headers to be sent to the server. If request takes longer. true. or exception thrown from main response handler. use GET and you could get different responses back from the same data If true then the URL is appended with a data. Timeout in milliseconds. Id of a form whose fields will be serialized to form the query data. Function to be called if request fails due to server error. and xhr. and an ioArgs object. Sent in the appropriate place depending on t ti ll S t i th i t l d di whether it is GET or POST. & and = inserted automatically. url. the error handler will be called instead of the load handler. query. json-comment-optional. query. dojo. Legal values are text. The address to req est Sho ld be a relati e URL request. jsoncomment-filtered. The object property names become request param names and property values get URLencoded and become request param values. url. but most useful are args. and an ioArgs object. Function gets passed 2 args: the data returned from the server (formatted according to the handleAs property). The ioArgs object has many properties. Function gets passed 2 args: the data returned from the server (formatted according to the handleAs property). Should the request be synchronous? Use synchronous requests with caution since they lock up the browser. g j g j has many properties. Should relative URL. and javascript. expired timeout. Function to be called whether or not request was successful. Default None N None preventCache Is browser prohibited from caching the page? Set to true if you false sync timeout url false Infinity None 46 . The ioArgs object p p y).Options Name content t t Description Data t D t to send t server.

resultRegion) { new Ajax. Developed and taught by well-known author and developer. resultRegion) { Ext. Ajax. } • Prototype function ajaxResult(address. GWT. At public venues or onsite at your location.load({ url: address}). Content-Centric Ajax with and without Toolkits • jQuery function ajaxResult(address. • Ext-JS 48 function ajaxResult(address. Spring.© 2009 Marty Hall Inserting Results into HTML: The “html” Function Customized Java EE Training: http://courses.load(address).com/ Servlets. } . Struts. Hibernate/JPA.Updater(resultRegion.coreservlets. JSF/MyFaces/Facelets. Response No li it tf t t t i Aj R handler uses “html” to do the insert.get(resultRegion). Java 5 & 6. resultRegion) { $(resultRegion). j p g } • Dojo – N explicit support for content-centric Ajax. address). JSP.

require("dojo.byId("id1").xhrGet({… content: { param1: dojo.value }).query("#params-button-2") .. thi I nothing equivalent to jQ i l t t jQuery’s $("# ’ $("#some-id"). id") l() 2. Supply values to “content” property – No need to escape values first • dojo.Reading Textfield Values 1. li k( h P 2) … }).byId("some-id").addOnLoad(function() { dojo. 50 .e.NodeList-html"). I. • Sh t t Shortcut – See upcoming section on “form” property 49 Ajax with HTML Insertion: JavaScript (Setup) dojo. since you are not doing a CSS match.onclick(showParams2). Use dojo. dojo.getElementById – Also note that Dojo has no way of looking up values directly from a NodeList resulting from a Dojo query.value – Note that there is no # before the ID. but rather using a shortcut for document.val().

} 51 HTML Insertion: HTML Page … <fieldset> <legend>dojo. param2: dojo byId("field2") value } dojo. load: function(text) { insertText(text. id of div whose innerHTML will become the result text. content: { param1: dojo. selector) { dojo.html(text).xhrGet({ dojo xhrGet({ url: "show-params.query(selector).Ajax with HTML Insertion: JavaScript (Main Code) function showParams2() { field1 and field2 are textfield ids (not names) dojo.byId("field1"). } }).jsp". } function insertText(text.value.xhrGet: HTML Insertion</legend> <form action="#"> param1: <input type="text" id="field1"/> <br/> param2: <input type="text" id="field2"/> <br/> <input type butto put type="button" value="Show Params" a ue S o a a s id="params-button-2"/> <h2 id="result1"></h2> </form> / </fieldset> … 52 .value }. "#result1").byId("field2").

param2}. param2 is ${param param2} ${param.param1}. Unchanged from previous example 53 HTML Insertion: Results 54 .HTML Insertion: JSP param1 is ${param.

} }). At public venues or onsite at your location.query(selector).xhrGet({ url: address. resultRegion) j ({ . Spring. .load(address). selector) { dojo. load: function(text) { insertText(text.Updater(resultRegion.coreservlets. jQuery Prototype jQuery.require) i ) function ajaxResult(address. resultRegion) { new Ajax. dojo. and Dojo • Prototype function ajaxResult(address.HTML Insertion: Comparing Prototype.html(text). resultRegion). Java 5 & 6. JSF/MyFaces/Facelets.com/ Servlets. } • jQuery function ajaxResult(address. JSP. Hibernate/JPA. GWT. resultRegion) { $(resultRegion). address). Ajax. Developed and taught by well-known author and developer. } 55 © 2009 Marty Hall Building Parameter Strings Automatically with “form” Customized Java EE Training: http://courses. } function insertText(text. Struts. } • D j (also need d j Dojo ( l d dojo.

# ). j G ({ .jsp . – The element names (not ids) become the param names • Syntax – dojo. load: …. url: "show-params. load: function(text) { ( .jsp". "#result2"). form: "form1".onclick(showParams3).g. function showParams3() { dojo. dojo. } }).Using “form” Option • Idea – You specify a form.addOnLoad(function() { dojo.require("dojo. insertText(text. and Dojo automatically builds query string from all appropriate input elements.xhrGet({ url: …. • Note: no # before the id • Advantages – One simple option.NodeList-html"). unchecked radio buttons or checkboxes are ignored) – Giving names to input elements is familiar to HTML developers 57 “form” Example: JavaScript dojo.. } … 58 . no matter how many input elements – Only takes values of active elements (e. . form: "some-id" }). onclick(showParams3).query("#params-button-3") . … }).xhrGet({ u : s o pa a s.

Unchanged from previous examples 60 .“form” Example: HTML … <fieldset> <legend>dojo.xhrGet: Simplifying Params with 'form'</legend> <form action="#" id="form1"> action= # id= form1 > param1: <input type="text" name="param1"/> <br/> param2: <input type="text" name="param2"/> <br/> b / <input type="button" value="Show Params" id="params-button-3"/> <h2 id="result2"></h2> / </form> </fieldset> … 59 “form” Example: JSP param1 is ${param.param2}.param1}. param2 is ${param param2} ${param.

JSF/MyFaces/Facelets. . GWT.com/ Servlets. Struts.“form” Example: Results 61 © 2009 Marty Hall Handling H dli JSON Data D t Customized Java EE Training: http://courses. At public venues or onsite at your location. Spring. JSP.coreservlets. Developed and taught by well-known author and developer. Ajax. Hibernate/JPA. Java 5 & 6.

handleAs: "json".g.bg.: • dojo.fg. function showNums() { j ({ dojo.addOnLoad(…). int dojo.g. Must build HTML from result. dojo addOnLoad( ).: • { cto: "Resig ".numbers). dojo.query("#result3").html("<b>Chief Technology Officer is " + companyExecutives.: i “ l” M b ild f l E • function handler(companyExecutives) { dojo. ceo: "Gates ".xhrGet – Specifies “json” for handleAs.xhrGet({ url: "show-nums". load: handler. handleAs: "json"}). coo: "Ellison" } • Code that calls dojo xhrGet dojo.html(list).query("#some-id") . } Strings 64 function showNumberList(jsonData) { var list = makeList(jsonData. j ({ j }) • Response handler – Receives JavaScript data as first argument. Array of doubles } .fontSize. load: showNumberList.xhrGet({url: address. preventCache: true }). No need for parsing or “eval”.cto + "</b>"). jsonData.Approach • Server – Returns JSON object with no extra parens.NodeList-html").require("dojo. E. jsonData. E.g. } 63 JSON Example Code: Core JavaScript dojo. E. jsonData fontSize jsonData.

} return(result). " + "font-size:" + fontSize + "px'>\n" + "<ul>\n"). " + "background-color:" + bg + ". } 65 JSON Example Code: Auxiliary JavaScript (Continued) function listItems(items) { var result = "".length.JSON Example Code: Auxiliary JavaScript function makeList(fg. bg. b (f bg. for(var i=0. i++) { result = result + "<li>" + items[i] + "</li>\n". } 66 . fontSize. . } function li tSt tT f ti listStartTags(fg. f tSi ) { fontSize) return( "<div style='color:" + fg + ". fontSize) + listItems(nums) + listEndTags()). } function listEndTags() { return("</ul></div>"). nums) { return( listStartTags(fg. bg. i<items.

Math. request. String fontSize = "" + (10 + ColorUtils.jsp". response).setAttribute("bg". bg).random().include(request.randomColor().setContentType("application/json").JSON Example Code: HTML … <fieldset> <fi ld t> <legend>dojo. HttpServletResponse response) throws ServletException. p ( g . dispatcher. nums). request. "no-cache"). request. response. "no-cache").random() request.randomColor(). double[] nums = { Math random() Math random() Math random() }.setHeader("Cache-Control". Math.xhrGet: Treating Response as JSON</legend> <form action="#"> <input type="button" value="Show Nums" id nums button /> id="nums-button"/> <div id="result3"></div> </form> </fieldset> </fi ld t> … 67 JSON Example Code: Servlet public class ShowNumbers extends HttpServlet { public void doGet(HttpServletRequest request.getRequestDispatcher(outputPage).setAttribute( bg .setHeader("Pragma". request. IOException { response. fontSize). }} 68 . response. ) String fg = ColorUtils.setAttribute("nums". fg). String bg = ColorUtils.random().setAttribute("fontSize".randomInt(30)). Math. String outputPage = "/WEB-INF/results/show-nums.setAttribute("fg". RequestDispatcher dispatcher = request.

"black". fontSize: ${fontSize}. "yellow" }. "fuchsia". "silver". inclusive. "lime".JSON Example Code: JSP { fg: "${fg}". "teal". "blue". "green". { [ ]}] } • Notes – No enclosing parens. "purple". "navy". ${nums[1]}. } /** One of the official HTML color names. "gray". ${nums[2]}] { [ ]}. numbers: [ ${nums[0]}.nextInt(range)). "olive". bg: "${b }" b "${bg}".length)]). "red". ( l [ d ( l l h)]) } } 70 . Dojo will wrap in parens and then pass to “eval” (or equivalent functionality) eval – Types • fg and bg: Strings • f tSi fontSize: i t int • numbers: Array of doubles 69 JSON Example Code: Auxiliary Java Code public class ColorUtils { p private static String[] colors = { g[] "aqua". */ public static int randomInt(int range) { return(new Random(). */ public static String randomColor() { return(colors[randomInt(colors. { [ ]}. "white". at random. "maroon". /** A random number between 0 and range-1.

Ajax. . At public venues or onsite at your location. Spring.coreservlets.com/ Servlets. GWT. Struts. JSP. Java 5 & 6.JSON Example: Results 71 © 2009 Marty Hall Wrap-up Customized Java EE Training: http://courses. Developed and taught by well-known author and developer. JSF/MyFaces/Facelets. Hibernate/JPA.

YUI. Dojo – 2nd tier: jQuery UI GWT UI. • Looking ahead – All these entries are likely to c ge s g c change significantly y – Lurking on the horizon: Google “Closure” library • Familiarity to JS developers 73 – Lowest: GWT Books and References • Dojo: The Definitive Guide – by Matthew A.org/docs – Moderately complete – Moderately well organized – Large number of explicit examples 74 . JSON-RPC • Other programming (Java) • Server communication • DOM manipulation – Leader: jQuery • Oth copying jQuery approach and Others i jQ h d closing gap. YUI. Russell • Mastering Dojo – b C i Ri k et al by Craig Riecke l • Concise Guide to Dojo – by Leslie M. Scriptaculous. jQuery released CSS matching library separately (http://sizzlejs.com) • Usage in industry – Leader: jQuery – 2nd tier: Ext-JS. Orchard M • http://dojotoolkit.“Best” JavaScript Libraries p • General JS programming – Leader: Prototype – Leader (only): GWT • Traditional Ajax support – Tie – Leader: GWT – 2nd tier: DWR. Prototype. Dojo. GWT • Rich GUIs – Leaders: Ext-JS.

function h dl F f ti handlerFunction(text) { ti (t t) dojo. . Developed and taught by well-known author and developer. JSP.query("#some-id"). Java 5 & 6. load: handlerFunction.NodeList-html").addOnLoad(function() { dojo.query("#some-id").onclick(someFunction). GWT.Summary • Assigning event handlers programmatically dojo.xhrGet({ … (omit handleAs) … }). Hibernate/JPA.coreservlets. dojo. Spring. At public venues or onsite at your location. . handleAs: "json" }). • Inserting HTML (content-centric Ajax) dojo. }).require("dojo.com/ Servlets. Struts. Ajax. • General Ajax requests (data-centric Ajax) dojo.xhrGet({ url: "relative-address". form: "form-id. JSF/MyFaces/Facelets. } 75 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.html(text).

Sign up to vote on this title
UsefulNot useful