SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
© 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
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.
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
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%.
© 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
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
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
Ajax.Request Example Code:
     JSP
     It is now <%= new java.util.Date() %>




17




     Ajax.Request: Results




18
© 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
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
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
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
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
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.
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
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
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
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
© 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
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
© 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
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
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
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
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
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
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.
“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
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.

Weitere ähnliche Inhalte

Was ist angesagt?

AEM and Sling
AEM and SlingAEM and Sling
AEM and SlingLo Ki
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartDavid Keener
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一scalaconfjp
 
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...Marco Antonio Maciel
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014Nayden Gochev
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modulesRafael Winterhalter
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6Yuval Ararat
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Anton Arhipov
 

Was ist angesagt? (20)

AEM and Sling
AEM and SlingAEM and Sling
AEM and Sling
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
13 java beans
13 java beans13 java beans
13 java beans
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
Django In The Real World
Django In The Real WorldDjango In The Real World
Django In The Real World
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChart
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Content Modeling Behavior
Content Modeling BehaviorContent Modeling Behavior
Content Modeling Behavior
 
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
 
The CoFX Data Model
The CoFX Data ModelThe CoFX Data Model
The CoFX Data Model
 
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
 

Andere mochten auch

neurisa_11_09_rosenthal
neurisa_11_09_rosenthalneurisa_11_09_rosenthal
neurisa_11_09_rosenthaltutorialsruby
 
RichFacesWhatIsNewIn330
RichFacesWhatIsNewIn330RichFacesWhatIsNewIn330
RichFacesWhatIsNewIn330tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 

Andere mochten auch (6)

69-kauri
69-kauri69-kauri
69-kauri
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 
neurisa_11_09_rosenthal
neurisa_11_09_rosenthalneurisa_11_09_rosenthal
neurisa_11_09_rosenthal
 
RichFacesWhatIsNewIn330
RichFacesWhatIsNewIn330RichFacesWhatIsNewIn330
RichFacesWhatIsNewIn330
 
manual-en
manual-enmanual-en
manual-en
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 

Ähnlich wie Prototype-1

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
java beans
java beansjava beans
java beanslapa
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalacheCodecamp Romania
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajaxs_pradeep
 

Ähnlich wie Prototype-1 (20)

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
Json generation
Json generationJson generation
Json generation
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Java script core
Java script coreJava script core
Java script core
 
14 mvc
14 mvc14 mvc
14 mvc
 
java beans
java beansjava beans
java beans
 
03 form-data
03 form-data03 form-data
03 form-data
 
Jersey and JAX-RS
Jersey and JAX-RSJersey and JAX-RS
Jersey and JAX-RS
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 

Mehr von tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascripttutorialsruby
 

Mehr von tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 

Kürzlich hochgeladen

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 

Kürzlich hochgeladen (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

Prototype-1

  • 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.