• Like
Prototype-1
Upcoming SlideShare
Loading in...5
×
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,105
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
12
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. © 2009 Marty Hall The Prototype Framework yp Part I: Ajax Support ( (Prototype 1.6 Version) yp ) 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, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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 – 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) • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, JSP, JSF 1.x & JSFEJB3, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. – Spring, Hibernate/JPA, 2.0, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Overview of Prototype • Installation and documentation • Ajax.Request – Basics – Options • HTML lookup and insertion • Ajax.Updater • Ajax.PeriodicalUpdater Ajax PeriodicalUpdater • Handling JSON Data • Comparing Ajax support to other libraries – jQuery, Dojo, Ext-JS 5 © 2009 Marty Hall Introduction Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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.
  • 3. Overview of Prototype • Ajax utilities – Ajax.Request, Ajax.Updater, Ajax.PeriodicalUpdater – Wraps response in Ajax.Response • Several new properties but especially responseJSON properties, • General DOM utilities – $() to find element – $F() to get form value – element.update() to put into innerHTML – Many helpers in Element class • General utilites –E t i Extensions for Class, Function, Array, String f Cl F ti A St i 7 Ajax Utilities • Ajax.Request – T k URL and options object (onSuccess and Takes d i bj ( S d parameters properties). – Calls URL, passes result (Ajax.Response) to onSuccess • Ajax.Updater – Takes id of result region and URL. – Invokes URL once and puts responseText in result region • Ajax.PeriodicalUpdater – Takes id of result region, URL, options object with g , , p j “frequency” property. Can call “stop” on updater later. • Ajax.Response – Passed to response handler functions – properties: responseText, responseXML, responseJSON 8
  • 4. Downloading and Installation • Download – h // http://www.prototypejs.org/download j /d l d • Download a single .js file (e.g., prototype-1.6.02.js) – Recommend renaming to prototype.js to simplify later upgrades • Thi t t i l corresponds t P t t This tutorial d to Prototype 1.6 16 • Online API – http://www.prototypejs.org/api p p yp j g p • Tips and Tutorials – http://www.prototypejs.org/learn • B Browser C Compatibility tibilit – Firefox: 1.5 or later – Internet Explorer: 6.0 or later (does not work in IE 5.5!) – Safari: 2.0 or later 9 – Opera: 9.25 or later Industry Usage Approximately 40% of matches to “prototype and JavaScript” were false positives such as “build a 10 prototype with JavaScript”. So, discount the Prototype graph by about 40%.
  • 5. © 2009 Marty Hall Ajax.Request: Ajax Request: Basics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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. Ajax.Request: Basic Syntax • new Ajax.Request(relative-url, options) – C ll relative-url, wraps response i Aj R Calls l i l in Ajax.Reponse, passes response to function specified in options • Note it is “new Ajax.Request(...)”, not “Ajax.Request(...)” • Options – An anonymous object – Most important property: onSuccess • Basic example – new Ajax.Request( "some-file.jsp", fil j {onSuccess: someHandlerFunction}); – someHandlerFunction should take one argument of type Ajax.Response. Ajax Response – It is automatically wrapped in anonymous function with local copy of request object, so it is threadsafe. 12
  • 6. Data-Centric Ajax with and without Toolkits • With basic JavaScript function getRequestObject() { if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else { return(null); } } function sendRequest() { var request = getRequestObject(); request.onreadystatechange = function() { someFunct(request); }; request.open("GET", "some-url", true); request.send(null); } 13 Data-Centric Ajax with and without Toolkits • jQuery (handler passed response text) $.ajax({url: "address", success: handlerFunct}); • Prototype (handler passed response object) new Ajax.Request("address", {onSuccess: handlerFunct}); • Ext (handler passed response object) Ext.Ajax.request({url: "address", success: handlerFunct}); • Dojo (handler passed response text) dojo.xhrGet({url: " dd d j h G t({ l "address"," load: handlerFunct}); 14
  • 7. Ajax.Request Example Code: JavaScript function showTime1() { new Ajax.Request( Ajax Request( "show-time.jsp", { onSuccess: showAlert }); } This i P t t Thi is a Prototype Ajax.Response object, Aj R bj t not the raw XmlHttpRequest. function showAlert(response) { alert(response.responseText); } 15 Ajax.Request Example Code: HTML ... <head><title>Prototype and Ajax</title>... Ajax</title> <script src="./scripts/prototype.js" type="text/javascript"></script> <script src="./scripts/prototype-examples.js" / / type="text/javascript"></script> </head> <body>... <fieldset> <legend>Ajax.Request: Basics</legend> g j q / g <form action="#"> <input type="button" value="Show Time" onclick= showTime1() /> onclick='showTime1()'/> </form> </fieldset> 16
  • 8. Ajax.Request Example Code: JSP It is now <%= new java.util.Date() %> 17 Ajax.Request: Results 18
  • 9. © 2009 Marty Hall Ajax.Request: Ajax Request: Passing Parameters g Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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. Ajax.Request Options { property1: v1 property2: v2 } v1, v2...} • The second arg is an anonymous object with these as the most important properties – onSuccess (default: none) • Response handler function (takes Ajax.Response as arg) • There are also many similar related options: onComplete onComplete, onFailure, onException, onXYX (for HTTP status codes) – parameters (default: empty string) • Can be explicit parameter string: "p1=val1&p2=val2" • Can also be parameter object: {p1: val1, p2: val2} – Values will be escaped automatically – asynchronous (default: true) – method (default: post) – evalJS (default: true) • Response text passed to “eval” if response type is application/javascript or a similar type pp j p yp – evalJSON (default: true) • Response text passed to eval (with parens added) and sent to 20 responseJSON if response type is application/json
  • 10. Ajax.Request Parameters Example Code: JavaScript function showParams1() { new Ajax.Request( Ajax Request( "show-params.jsp", { onSuccess: showAlert, parameters: "param1=foo&param2=bar" }); } function showAlert(response) { alert(response.responseText); } 21 Ajax.Request Parameters Example Code: HTML and JSP <fieldset> <legend>Ajax.Request: <legend>Ajax Request: The 'parameters' Option</legend> <form action="#"> <input type="button" value="Show Params" onclick='showParams1()'/> </form> </fieldset> 22
  • 11. Ajax.Request Parameters Example Code: HTML and JSP • HTML <fieldset> <legend>Ajax.Request: The 'parameters' Option</legend> p p g <form action="#"> <input type="button" value="Show Params" onclick showParams1() /> onclick='showParams1()'/> </form> </fieldset> • JSP (show-params.jsp) param1 is ${param param1} ${param.param1}, param2 is ${param.param2}. 23 Ajax.Request Parameters: Results 24
  • 12. Utilities for Reading and Writing HTML Elements • $("id") – Returns element with given id [getElementById("id")] • Can also take an Element instead of an element id • Can also take multiple arguments, in which case it returns an array of the Element results • Yes, “$” is really the function name • $F("id") $F( id ) – Returns value of form element with given ID • Single value for most elements, array for multi-select lists g , y • For textfields, equivalent to $("id").value • update("html-string") – Inserts i into innerHTML property i – E.g., $("result-region").update("<h1>Test</h1>") 25 Building Parameter Strings • The $F function does not escape values – S this could yield illegal results So, hi ld i ld ill l l • { onSuccess: someHandlerFunction, parameters: "param1=" + $F("field1") } – If field 1 contains spaces, ampersands, etc., this causes problems fi ld t i d t thi bl – You could do escape($F("field1")), but this gets a bit verbose • Instead of a parameter string, you can supply parameter object l t bj t – { param1: "val1", param2: "val2" ... } – Values (usually from $F(...)) are automatically escaped, then whole thing converted to parameter string – You can also do this explicitly anywhere with $H function that creates Hash, and toQueryString method Hash • $H({p1: "val1", p2: "val2"}).toQueryString() returns "p1=val1&p2=val2" 26
  • 13. Ajax.Request: Reading/Writing Utils Example Code: JavaScript function showParams2() { Original (not escaped) value of textfield whose id (not name) is “field1”. var params = { param1: $F("field1"), param2: $F("field2") }; new Ajax.Request( "show-params.jsp", { onSuccess: updateResult, parameters: params }); Parameter object is converted } to parameter string with escaped values. function updateResult(response) { $("result1").update(response.responseText); } Inserts into innerHTML property. Finds element whose id is "result1". 27 Ajax.Request: Reading/Writing Utils Example Code: HTML <fieldset> <legend>Ajax.Request: <legend>Ajax Request: Reading/Writing Utilities</legend> <form action="#"> param1: <input type="text" id="field1"/> <br/> param2: <input type="text" id="field2"/> / <br/> <input type="button" value="Show Params" onclick='showParams2()'/> <h2 id="result1"></h2> id= result1 ></h2> </form> </fieldset> 28
  • 14. Ajax.Request: Reading/Writing Utils: Results 29 © 2009 Marty Hall Ajax.Updater Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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.
  • 15. Ajax.Updater: Basic Syntax • new Ajax.Updater(result-id, url, options) – Calls URL – Extracts resultText – Puts it into innerHTML of element with result-id result id • Options – An anonymous object just as with Ajax.Request object, Ajax Request – Most important property: parameters – No onSuccess usually needed 31 Content-Centric Ajax with and without Toolkits (Basic JS Only) function getRequestObject() { ... } function ajaxResult(address, resultRegion) { var request = getRequestObject(); request.onreadystatechange = function() { showResponseText(request, resultRegion); }; request.open("GET", address, true); request.send(null); request send(null); } function showResponseText(request, resultRegion) { p ( q , g ) if ((request.readyState == 4) && (request.status == 200)) { document.getElementById(resultRegion).innerHTML = request.responseText; t T t } } 32
  • 16. Content-Centric Ajax with and without Toolkits (Ajax Request) (Ajax.Request) function ajaxResult(address, resultRegion) { new Ajax Request( Ajax.Request( address, { onSuccess: function(response) { showResponseText(response, resultRegion); } }); } function showResponseText(response, resultRegion) { u ct o s o espo se e t( espo se, esu t eg o ) $(resultRegion).update(response.responseText); } 33 Content-Centric Ajax with and without Toolkits (Libraries) • jQuery function ajaxResult(address, resultRegion) { $(resultRegion).load(address); } • Prototype function ajaxResult(address, resultRegion) { new Ajax.Updater(resultRegion, address); j p ( g , ); } • Dojo – No explicit support for content-centric Ajax l f • Ext-JS function ajaxResult(address resultRegion) { ajaxResult(address, Ext.get(resultRegion).load({ url: address}); } 34
  • 17. Ajax.Updater Example Code: JavaScript function showParams3() { var params = { param1: $F("param3"), param2: $F("param4") }; id of element into whose innerHTML new Ajax.Updater( the responseText is inserted "result2", "show-params.jsp", { parameters: params }); } • Notes – No onSuccess normally needed – Can update a single element only. If you need to update more, use Ajax.Request Ajax Request with onSuccess • You could also return script from server, but then server needs to know name of DOM elements 35 Ajax.Updater Example Code: HTML <fieldset> <legend>Ajax.Updater</legend> <legend>Ajax Updater</legend> <form action="#"> param1: <input type="text" id="param3"/> / <br/> param2: <input type="text" id="param4"/> <br/> <input type="button" value="Show Params" p yp onclick='showParams3()'/> <h2 id="result2"></h2> </form> </fieldset> 36
  • 18. Ajax.Updater: Results 37 Ajax.Updater Options • evalScripts – Should <script> tags in the response be evaluated? – Default is false, so this option is very important if you return <script> tags that set event handlers (e.g. for scriptaculous in-place editors) for elements that are inserted ) • insertion – Where text should be inserted relative to what is already there. – Default is to replace any existing content. – Options are 'top', 'bottom', 'before', 'after' • Standard options still supported – parameters onSuccess, etc parameters, onSuccess etc. • Example – var params = { param1: "foo", param2: "bar" }; – new Ajax Updater("some id", "some address", Ajax.Updater( some-id some-address { evalScripts: true, insertion: 'top', parameters: params }); 38
  • 19. © 2009 Marty Hall Ajax.PeriodicalUpdater Aj P i di lU d t Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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. Ajax.PeriodicalUpdater Example Code: JavaScript var updater; // Save ref so can "stop" later function showTime2() { updater = new Ajax.PeriodicalUpdater( "result3", "show-time.jsp", { frequency: 5 }); } 40
  • 20. Ajax.PeriodicalUpdater Example Code: HTML <fieldset> <legend>Ajax.PeriodicalUpdater</legend> <legend>Ajax PeriodicalUpdater</legend> <form action="#"> <h2 id="result3"></h2> <script type="text/javascript"> / showTime2(); </script> <input type="button" value="Stop Updates" onclick='updater.stop()'/> / </form> </fieldset> • Note – Form needed only if you want to let user stop the action 41 Ajax.PeriodicalUpdater: Results 42
  • 21. © 2009 Marty Hall Handling H dli JSON Data D t Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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. Ajax.Response Properties • The arg passed to response handler has these as most important properties – status, statusText • HTTP status code and corresponding text – responseText • Same as normal XmlHttpRequest.responseText – responseXML espo se • Same as normal XmlHttpRequest.responseXML – responseJSON • Response text wrapped in parens and passed to "eval"eval • Only available if response type is application/json – headerJSON • Evaluated content of X-JSON response header • Alternative for responseJSON for small amounts of data 44
  • 22. Ajax.Response Methods • Can also call these methods on response – getHeader(responseHeaderName) • Gets header value. • Does not throw exception if header missing (unlike native XmlHttpResponse method) – getAllHeaders() • Returns a string with all headers delimited by newlines headers, • Does not throw exception if there are no headers – getResponseHeader, getAllResponseHeaders • Native version of above methods • Throws exceptions if headers missing • Used only with preexisting code that handled exeptions. y p g p Use getHeader and getAllHeaders otherwise 45 Using JSON Data with responseJSON property • Response object properties – responseText, responseXML, and responseJSON – Response object passed to handler function (designated with onSuccess, etc ) onSuccess etc.) – For more details see Ajax.Response in online API • Behavior – Response text wrapped in parens and passed to "eval" • Server returns { prop1: val1, prop2: val2 } without parens • R Requirements i t – responseJSON populated only if response type is application/json 46
  • 23. responseJSON Example Code: Core JavaScript function showNums() { new Ajax.Request( Ajax Request( "show-nums", { onSuccess: showNumberList, Strings method: "get" }); } function showNumberList(response) { var obj = response.responseJSON; var list = makeList(obj.fg, obj.bg, ( j g, j g, obj.fontSize, obj.numbers); $("result4").update(list); } Array of doubles Integer 47 responseJSON Example Code: Auxiliary JavaScript function makeList(fg, bg, fontSize, nums) { return( listStartTags(fg, bg, fontSize) + listItems(nums) + listEndTags()); } function li tSt tT f ti listStartTags(fg, b (f bg, f tSi ) { fontSize) return( "<div style='color:" + fg + "; " + "background-color:" + bg + "; " + "font-size:" + fontSize + "px'>n" + "<ul>n"); } 48
  • 24. responseJSON Example Code: Auxiliary JavaScript (Continued) function listItems(items) { var result = "";; for(var i=0; i<items.length; i++) { result = result + "<li>" + items[i] + "</li>n"; } return(result); } function listEndTags() { return("</ul></div>"); } 49 responseJSON Example Code: HTML <fieldset> <legend>Ajax.Request: <legend>Ajax Request: responseJSON</legend> <form action="#"> <input type="button" value="Show Nums" onclick='showNums()'/> / <div id="result4"></div> </form> </fieldset> 50
  • 25. responseJSON Example Code: Servlet public class ShowNumbers extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); p ( g , ) String fg = ColorUtils.randomColor(); request.setAttribute("fg", fg); String bg = ColorUtils.randomColor(); request.setAttribute( bg , request.setAttribute("bg", bg); String fontSize = "" + (10 + ColorUtils.randomInt(30)); request.setAttribute("fontSize", fontSize); double[] nums = { Math random() Math random() Math random() }; Math.random(), Math.random(), Math.random() request.setAttribute("nums", nums); response.setContentType("application/json"); String outputPage = "/WEB-INF/results/show-nums.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(outputPage); dispatcher.include(request, response); 51 }} responseJSON Example Code: JSP { fg: "${fg}", bg: "${b }" b "${bg}", fontSize: ${fontSize}, numbers: [ ${nums[0]}, ${nums[1]}, ${nums[2]}] { [ ]}, { [ ]}, { [ ]}] } • Notes – Client-side code does not need wrap in parens and pass to “eval”. JSON evaluation handled automatically by eval . Prototype – Types • f and b St i fg d bg: Strings • fontSize: int 52 • numbers: Array of doubles
  • 26. JSON Example Code: Auxiliary Java Code public class ColorUtils { p private static String[] colors = { g[] "aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "purple", "red", "silver", "teal", "white", "yellow" }; /** One of the official HTML color names, at random. */ public static String randomColor() { return(RandomUtils.randomElement(colors)); } private ColorUtils() {} // Uninstantiatable class} } 53 JSON Example Code: Auxiliary Java Code public class RandomUtils { private static Random r = new Random(); public static int randomInt(int range) { return(r.nextInt(range)); return(r nextInt(range)); } public static int randomIndex(Object[] array) { return(randomInt(array.length)); } public static <T> T randomElement(T[] array) { return(array[randomIndex(array)]); } } 54
  • 27. responseJSON Example: Results 55 © 2009 Marty Hall Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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.
  • 28. “Best” JavaScript Libraries p • General JS programming • Traditional Ajax support – Leader: Prototype – Tie • Other programming (Java) • Server communication – Leader (only): GWT – Leader: GWT • DOM manipulation – 2nd tier: DWR, JSON-RPC – Leader: jQuery • Usage in industry • Oth copying jQuery approach and Others i jQ h d – Leader: jQuery closing gap. jQuery released CSS matching library separately – 2nd tier: Ext-JS, Dojo, YUI, (http://sizzlejs.com) Prototype, Scriptaculous, GWT • Rich GUIs • Looking ahead – Leaders: Ext-JS, YUI, Dojo – All these entries are likely to – 2nd tier: jQuery UI GWT UI, c ge s g c change significantlyy – Lurking on the horizon: • Familiarity to JS developers Google “Closure” library 57 – Lowest: GWT Recommended Books • Prototype and script.aculo.us: You Never Knew J K JavaScript C ld Do Thi ! S i Could D This! – By Christophe Porteneuve • Prototype and Scriptaculous in Action – By Dave Crane, Bear Bebeault, Tom Locke 58
  • 29. Summary • Ajax.Request – new Aj R Ajax.Request("url", { onSuccess: h dl ... }) (" l" S handler, }); • Also has parameters option (string or object) • Don't forget the “new”" • Ajax.Updater – new Ajax.Updater("id", "url", {options}); • Ajax.PeriodicalUpdater – new Ajax.PeriodicalUpdater("id", "url", { frequency: ...}); • Ajax.Response – Has responseJSON property SO • Utility function – $("some-id")  Element with that id ( ) – $F("some-id")  Value of Element with that id – someElement.update("html") – inserts in innerHTML 59 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, 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.