SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
© 2009 Marty Hall




   The jQuery JavaScript Library
       j      y          p     y
         Part I: Ajax Support
                                       (j
                                       (jQuery 1.3 Version)
                                             y            )
             Originals of Slides and Source Code for Examples:
       http://courses.coreservlets.com/Course-Materials/jquery.html
          p                                             jq y
                  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 jQuery
    •   Installation and documentation
    •   Quick summary of jQuery selectors
    •   Data centric Ajax: the “$.ajax” function
         – Basics
         – O ti
           Options
         – Sending data
    • Content-centric Ajax: the “load” function
                                 load
    • Handling JSON data
    • Comparing Ajax support to other libraries
         – Prototype, 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 jQuery
    • Ajax utilities (this tutorial)
       – General: $.ajax(…), $(…).load(…)
       – Shortcuts: $.get, $.post, $.getJSON
    • DOM search and manipulation utilities
       – $("p.myStyle").addClass("extraStyle").show();
    • Simple animation
       – Not as extensive as Scriptaculous, but easy to use
    • Cross-browser event model
       – A i
         Assigns h dl programmatically, hides browser differences
                 handlers      ti ll hid b            diff
    • General JavaScript utilities
       – Functions operating on strings and arrays
    • Rich GUIs
7
       – jQuery UI provides widgets, fancier effects, drag/drop




     Ajax Utilities
    • $.ajax({options})
       – Makes an Ajax request. Example:
          • $.ajax({ url: "address", success: responseHandler});
          • The response handler is passed the response text, not the
            response object. Don’t forget the “.” before “ajax”!
    • load(url)
       – Makes Ajax request and loads result into HTML element
           k    j             dl d        l i           l
          • $("#some-id").load("address");
          • A data string or object is an optional second arg
                        g      j           p                g
    • Shortcuts
       – $.get, $.post, $.getJSON
          • Slightly simpler forms of $.ajax. However, as of jQuery 1.3,
            they take data objects but not data strings, so you can’t
8
            use “serialize”. So, $.ajax is better.
Downloading and Installation
     • Download
       – http://docs.jquery.com/Downloading_jQuery
             • Download single minimized file (e.g., jquery-1.3.2.min.js)
                   – Recommend renaming to jquery.js to simplify later upgrades
     • Online API and tutorials
       – http://docs.jquery.com/
     • Browser Compatibility
       –   Firefox: 2 or later (vs. 1.5 or later for Prototype)
       –   Internet Explorer: 6.0 or later (does not work in IE 5.5)
                               60                                5 5)
       –   Safari: 3.0 or later (vs. 2.0 or later for Prototype)
       –   Opera: 9.0 or later (vs. 9.25 or later for Prototype)
       –   Chrome: 1.0 or later
       –   To check, run the test suite at http://jquery.com/test/
9




     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




                    jQuery Selectors:
                         Basics
                              Note: brief intro only. More details in next tutorial section.




                       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.




     Selecting DOM Elements
     • Idea
       – U $(" selector") to get a set of DOM elements
         Use $("css l  ")               f      l
          • Then, perform operations on each (see next page)
          • Much more detail given in next tutorial section
     • Examples
       – $("#some-id")
          • Return 1-element set (or empty set) of element with id
                   1 element
          • Simplest use, and most common for Ajax (note the “#”!)
       – $("p")
          • Return all p elements
       – $(".blah")
          • Return all elements that have class="blah"
       – $("li b span blah")
                 span.blah")
          • Return all <span class="blah"> elements that are inside b
            elements, that in turn are inside li elements
12
Manipulating DOM Elements
     • Common functions on matched elements
        – $("#
          $("#some-id").val()
                   id") l()
           • Returns value of input element. Used on 1-element sets.
        – $("selector").each(function)
           • Calls function on each element “this” set to element
                                    element. this         element.
        – $("selector").addClass("name")
           • Adds CSS class name to each. Also removeClass, toggleClass
        – $("selector") hide()
          $( selector ).hide()
           • Makes invisible (display: none). Also show, fadeOut, fadeIn, etc.
        – $("selector").click(function)
           • Adds onclick handler Also change focus mouseover etc
                          handler.     change, focus, mouseover, etc.
        – $("selector").html("<tag>some html</tag>")
           • Sets the innerHTML of each element. Also append, prepend
     • Chaining
        – $("a").click(funct1).addClass("name").each(funct2)
13




      Example: Randomizing
      Background Colors (JavaScript)
     function randomizeHeadings() {                Call setRandomStyle function on each h3 element
       $( h3 ).each(setRandomStyle);
       $("h3") each(setRandomStyle);
       $("h3.green").hide("slow");
     }                                            Slowly hide every h3 that has CSS style “green”


     function setRandomStyle() {
       $(this).addClass(randomStyle());
     }
                                                   Add “red”, “yellow” or “green” CSS names to each
     function randomStyle() {
       var sty es = [ ed , "yellow", "green"];
        a styles    ["red", ye o , g ee ];
       return(randomElement(styles));
     }
     function randomElement(array) {
                           (    y)
       var index = Math.floor(Math.random()*array.length);
       return(array[index]);
14   }
Example: Randomizing Colors
     (JavaScript Continued)
     function revertHeadings() {
       $( h3.green ).show( slow );
       $("h3 green") show("slow");
       $("h3").removeClass("red").removeClass("yellow")
                                 .removeClass("green");
     }
                                         Like smart window.onload. Explained in next section.


     $(function() {
         $("#button1").click(randomizeHeadings);
         $("#b tt 1") li k(     d i H di      )
         $("#button2").click(revertHeadings);
     });
                                                                                   Sets onclick handlers




15




     Example: Randomizing Colors
     (Style Sheet)
     .red { background-color: red }
     .yellow { background-color: yellow }
      yellow
     .green { background-color: green }

     …

         Names set by setRandomStyles function




16
Example: Randomizing Colors
      (HTML)
     …
     <head><title>jQuery Basics</title>
     <link rel="stylesheet"
           href="./css/styles.css" Renamed from jquery-1.3.2.min.js
           type="text/css"/>
     <script src="./scripts/jquery.js"
             type="text/javascript"></script>
     <script src="./scripts/jquery-basics.js"
     <   i t     " /   i t /j      b i             j "
             type="text/javascript"></script>
     </head>




17




      Example: Randomizing Colors
      (HTML Continued)
     …
     <h3>Foo, bar,
     <h3>Foo bar baz</h3>
     <h3>Blah, blah, blah</h3>
     <h3>Yadda, yadda, yadda</h3>
     <h3>Foo, bar,
     <h3>Foo bar baz</h3>
     <h3>Blah, blah, blah</h3>
     <h3>Yadda, yadda, yadda</h3>
     <h3>Foo, b
     <h3>F    bar, b </h3>
                   baz</h3>
     <h3>Blah, blah, blah</h3>
                                                           The ids to which click
     <h3>Yadda, yadda, yadda</h3>                          handlers were attached.

     <form action="#">
                   #
       <input type="button" id="button1"
              value="Randomize Headings"/>
       <input type="button" id="button2"
              value="Revert Headings"/>
18   </form> …
Example: Randomizing Colors
     (Results)
                                                                After “Randomize Headings”. Some headings turned
                                                                green, then gradually disappeared.




      When page originally loaded, or after “Revert Headings”
19




     Understanding Operations on
     Sets of Elements
     • Instead of this
         function randomizeHeadings() {
           $("h3").each(setRandomStyle);
           $("h3.green").hide("slow");
           $("h3 green") hide("slow");
         }
         function setRandomStyle() {
                               y ()
           $(this).addClass(randomStyle());
         }
     • Why can’t I simply do this?
         function randomizeHeadings() {
           $("h3").addClass(randomStyle())
           $("h3") ddCl ( d St l ())
           $("h3.green").hide("slow");
20
         }
© 2009 Marty Hall




                            $.ajax: 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: Basic Syntax
     • $.ajax(optionsObject)
       – Minimal form: $.ajax({url: "address", success: funct});
          • Don’t forget the “.”. It is $.ajax(…), not $ajax(…).
       – The handler function gets the response text, not the
         response object. jQuery figures out if it should be plain
         text or XML from the response type. If you want the
                                         type
         handler to get JSON, use dataType option
     • Options for $.ajax({…})
        p          $ j ({ })
       – Almost-always used
          • url, success
       – Other common options
          • cache, data, dataType, error, type, username, password
22
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);
       }
23




     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});
24
$.ajax Example Code:
      JavaScript
     function showTime1() {
       $.ajax({
       $ ajax({ url: "show time jsp"
                     "show-time.jsp",
                success: showAlert,
                cache: false });
                                   The cache option is not required but is a convenient
                                                           required,
     }                             option when the same URL (including query data) yields
                                                       different responses. This way, you don’t have to send
                                                       Cache-Control and Pragma headers from server.
     function showAlert(text) {
       alert(text);
     }                                                  This is the response text, not the response object
                                                        (XmlHttpRequest). Also note that the latest Firefox
                                                        does not let you pass native functions here, so you
                                                        cannot use alert instead of showAlert for the success
                                                        parameter.




25




      $.ajax Example Code:
      HTML
     ...
     <head><title>jQuery and Ajax</title>...
                              Ajax</title>
     <script src="./scripts/jquery.js"
             type="text/javascript"></script>
     <script src="./scripts/jquery-ajax.js"
             src=" /scripts/jquery ajax js"
             type="text/javascript"></script>
     </head>
     <body>...
     <b d >
     <fieldset>
       <legend>$.ajax: Basics (Using onclick
                handler in HTML)</legend>
       <form action="#">
         <input type="button" value="Show Time"
                 onclick='showTime1()'/>
                    li k ' h Ti 1()'/>
       </form>
26
     </fieldset>
$.ajax Example Code:
     JSP
     It is now <%= new java.util.Date() %>




27




     $.ajax: Results




28
Registering Event Handlers in
     JavaScript
     • Basic approach
       – Previous example set the onclick handler in the HTML.
         Although this is common with some Ajax libraries,
         jQuery advocates setting it in the JavaScript instead
          • Often referred to as “unobtrusive JavaScript”: no explicit
            JavaScript anywhere in the HTML page
     • jQuery support
       – $(function() {…});
          • Function runs after the DOM is loaded, but does not wait
                                                   ,
            for images, as with window.onload
          • Use this approach to set up all event handlers
       – $("#some-id") click(someHandler);
         $( #some id ).click(someHandler);
          • Assigns to onclick handler. Handler is passed an Event
            object with characteristics that are unified across browsers
29




     Redoing Time Alert: JavaScript
     $(function() {
         $("#time-button-1").click(showTime1);
         $("#time button 1") click(showTime1);
     });


     function showTime1() {
       $.ajax({ url: "show-time.jsp",                      These two functions
                success: showAlert,                        are unchanged from
                                                           previous example.
                cache: false });
     }

     function showAlert(text) {
       alert(text);
     }
30
Redoing Time Alert: HTML
     <fieldset>
       <legend>$.ajax:
       <legend>$ ajax: Basics (Using click
                function in JavaScript)</legend>
       <form action="#">
         <input type="button" value="Show Time"
                 id='time-button-1'/>
       </form>
     </fieldset>




31




     Redoing Time Alert: Results




                       Works exactly the same as previous example
                                                          example.




32
© 2009 Marty Hall




                                $.ajax:
                                $ ajax:
                             Sending Data
                                    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.




     Overview
     • $.ajax({ url: …, success: …, data: …});
       – Can be a String, in which case it is sent unchanged.
          • On end of URL or in POST data, depending on HTTP type
          • See later example for building the string automatically
            using the “serialize” function
       – Can be an object, in which case query string gets built out
         of property names and URL-encoded property values
                                URL encoded
          • Works identically to “parameters” option in Prototype
     • Equivalent examples
        q             p
       – $.ajax({… data: "param1=foo+bar%21&param2=baz"});
       – $.ajax({… data: { param1: "foo bar!", param2: "baz"}});


34
Data Example: JavaScript
     $(function() {
         $("#params-button-1").click(showParams1);
         $("#params button 1") click(showParams1);
         …
     });

     function showAlert(text) {
       alert(text);
     }
                                   Same function used in earlier examples.

     function showParams1() {
                         ()
       $.ajax({ url: "show-params.jsp",
                data: "param1=foo&param2=bar",
                success: showAlert });
     }
                                  The cache option is not used since the same data always
                                  results in the same response.
35




     Data Example: HTML
     …
     <fieldset>
       <legend>$.ajax: The 'data' Option</legend>
       <form action="#">
         <input type="button" value="Show Params"
                id='params-button-1'/>
       </form>
     </fieldset>




36
Data Example: JSP
     param1 is ${param.param1},
     param2 is ${param param2}
               ${param.param2}.




37




     Data Example: Results




38
© 2009 Marty Hall




                $.ajax:
                $ ajax:
         Options and Shortcuts
          p

                       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
     • Options (almost) always used: url, success
       – $.ajax({url: "some-address", success: someFunction});
          • success is not strictly required; you might want to just fire
            off some data to the server and not display anything
                                                    p y y        g
     • Common options: example
       $.ajax({
           url: " dd
             l "address","
           success: successHandlerFunction,
           data: { param1: "foo bar", param2: "baz"},
           error: errorHandlerFunction,
           cache: false,
           dataType: "json",
                yp    j    ,
           username: "resig",
           password: "scriptaculous-fan" });
40
Options
        Name                                    Description                                     Default
        async        Should th
                     Sh ld the request be asynchronous? U synchronous requests with
                                       tb        h      ? Use h             t ith                  true
                                                                                                   t
                     caution since they lock up the browser.
     beforeSend Function to modify XMLHttpRequest object before it is sent (e.g.,                 None
                     to set custom headers). The XHR is automatically passed to
                     function.
        cache        Is browser permitted to cache the page? Set to false if you use GET           true
                     and you could get different responses back from the same data.            (except false if
                     Equivalent to having the server send Cache Control: no cache and
                                                          Cache-Control: no-cache             dataType is script
                     Pragma: no-cache.                                                             or json)

      complete       Function to be called after error or success function is finished.           None
     contentType Content-Type of data sent to server. Rarely needed.
                 Content Type                                                                    application/
                                                                                                  pp
                                                                                                x-www-form-
                                                                                                 urlencoded
         data        Data to send to server (possibly after conversion). Sent in the             Empty
                     appropriate place depending on whether it is GET or POST. Can be
                     a String or an object. If a String, sent unchanged. If an object,
                     property names become param names and property values get URL-
                     encoded and become param values. & and = inserted automatically.
41




      Options (Continued)
        Name                                    Description                                     Default
      dataFilter
      d t Filt       Response-data sanitizing function. R l used.
                     R        d t     iti i f ti        Rarely d                                  None
                                                                                                  N
      dataType       The format in which to pass the response to the handler function.        html or xml
                     Legal values are text, html (same as text except embedded scripts        (makes intelligent
                     are run), xml, json, jsonp (JSON with Padding), and script
                            ),    ,j ,j p(                         g),         p                  guess)
                     (evaluates the response as JavaScript and returns it as plain text).
         error       Function to be called if request fails. Function is passed 3 args: the       None
                     XHR object, a string describing the error type, and an optional
                     exception object. Possible values for the second argument are null,
                               object                                                 null
                     "timeout", "error", "notmodified" and "parsererror".
        global       jQuery lets you set global defaults for various handlers: should they         true
                     be used if set?
      ifModified     Should the request be considered successful only if the response has          false
                     changed since the last request (based on the Last-Modified header)?
        jsonp        Override the callback function name in a jsonp request. JSONP is a         callback
                     JSON extension in which the name of a callback function is
                            e tension      hich                         f nction
                     specified as an input argument of the call itself.
      password       Username and password to be used in response to HTTP                         None
42    username       authentication request.
Options (Continued)
         Name                                    Description                                   Default
     processData
            D t        Should th
                       Sh ld the value of th “data” property, if an object, be turned into
                                   l    f the “d t ”      t          bj t b t       di t          true
                                                                                                  t
                       a URL-encoded query string?
     scriptCharset Forces the request to be interpreted as a certain charset. Only for           None
                       requests with dataType of “jsonp” or “script” and type of “GET”.
        success        Function to be called if request succeeds. Function gets passed 2         None
                       args: the data returned from the server (formatted according to the
                       dataType property), and a string describing the status.
        timeout
        ti    t        Timeout in milliseconds. If request takes longer, the error handler
                       Ti       i    illi     d               k l         h        h dl      Global timeout, if
                                                                                             Gl b l ti    t
                       will be called instead of the success handler.                             set via
                                                                                               $.ajaxSetup
          type         The HTTP method to use for the request. “get” and “post” are                get
                       main options, but some browsers support other methods.
                         i     i     b        b                  h      h d
           url         The address to request. Should be a relative URL.                         None
           xhr         Callback for creating your own custom XMLHttpRequest object.          ActiveXObject if
                                                                                              available (IE)
                                                                                                        (IE),
                                                                                             XMLHttpRequest
                                                                                                otherwise

43




      Shortcuts for $.ajax:
      Equivalent Forms
     • $.get
          – $ (" l" d Obj someFunct)
            $.get("url", dataObj,       F     )
          – $.ajax({url: "url", data: dataObj, success: someFunct});
     • $.post
          – $.post("url", dataObj, someFunct)
          – $.ajax({url: "url", data: dataObj, success: someFunct,
                    type: "post"});
                            post });
     • $.getJSON
          – $.getJSON("url", dataObj, someFunct)
              g        (      ,        j,           )
          – $.ajax({url: "url", data: dataObj, success: someFunct,
                    dataType: "json"});
     • Note
          – get and post take the type as an optional fourth argument
44
Pros and Cons of Shortcuts
     • Advantages of shorthand functions
       – Slightly shorter and (arguably) clearer
     • Disadvantages of shorthand functions
       – Th data cannot be a string. This means you cannot use
         The d             b       i   Thi
         the serialize function (discussed later) to automatically
         build the query string from the form
                    q y        g
       – If you want additional options later, you have to change
         existing code more drastically
       – If you don’t have data you have to pass in null. This is
                             data,                     null
         less convenient than just omitting the “data” property.
          • $.get("url", null, someHandler);                                             vs.
          • $.ajax({url: "url", success: someHandler});

45




                                                                                                  © 2009 Marty Hall




        Simplifying Inserting Results
           p y g            g
                 into HTML:
            the “load” Function
                  load

                       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.
load: Basic Syntax
     • Basic forms
        – $("#result-area-id").load("url");
        – $("#result-area-id").load("url", data);
        – $("#result area id") load("url" data handlerFunction);
          $("#result-area-id").load("url", data,
     • Helper utilities
        – val: reading the value of an input element
           • var text = $("#some-textfield-id").val();
           • Works for all input elements, even multiselectable select
             elements (in which case it returns an array)
        – Filtering returned HTML
           • Add jQuery selectors to the URL. Only elements that
             match will b i
               t h ill be inserted. E
                               t d E.g., t i
                                         to insert only li elements:
                                                 t l        l    t
              – $("#result-id").load("address li");
47
              – Go very light with filtering: use data-centric Ajax instead.




      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
       }
     }
48
Content-Centric Ajax with and
     without Toolkits ($ ajax)
                      ($.ajax)
     function ajaxResult(address, resultRegion) {
       $.ajax({
       $ ajax({
         url: address,
         success: function(text) {
                    showResponseText(text,
                    showResponseText(text resultRegion);
                  }
       });
     }

     function showResponseText(text, resultRegion) {
       $(resultRegion).html(text);
       $(            )     (    )
     }

                                      Note: use the “html” function (as above) to replace the
                                      innerHTML of the element. Use “append” to add to the
                                      end of the innerHTML of the element.

49




     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 expl
               licit support for content-centric Ajax
                             f
     • Ext-JS
       function ajaxResult(address resultRegion) {
                ajaxResult(address,
         Ext.get(resultRegion).load({ url: address});
       }
50
load Example 1: JavaScript
     $(function() {
         $("#params-button-2").click(showParams2);
         $("#params button 2") click(showParams2);
         …
     });                            field1 and field2 are textfield ids (not names)



     function showParams2() {
       var params =
         { param1: $("#field1").val(),
            param2: $("#field2").val() };
       $( #
       $("#result1").load("show-params.jsp", params);
                    )     (      p      j p , p    );
     }


           id of div whose innerHTML will become the result text.



51




      load Example 1: HTML
     ...
     <fieldset>
       <legend>$.load: Simplifying HTML Insertion</legend>
       <form action="#">
         param1:
         <input type="text" id="field1"/>
         <br/>
         param2:
         <input type="text" id="field2"/>
         <br/>
            /
         <input type="button" value="Show Params"
                 id="params-button-2"/>
         <h2 id="result1"></h2>
              id= result1 ></h2>
       </form>
     </fieldset>
52
load Example 1: JSP
     param1 is ${param.param1},
     param2 is ${param param2}
               ${param.param2}.




            Unchanged from previous example




53




     load Example 1: Results




54
© 2009 Marty Hall




        Building Parameter Strings
       Automatically with “serialize”

                       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.




     Using “serialize”
     • Idea
       – You specify a form, and jQuery automatically builds
         query string from all appropriate input elements.
       – The element names (not ids) become the param names
     • Syntax
       – $("result-id").load("url", $("#form-id").serialize());
         $(           )     (     , $(          )          ());
     • Advantages
       – One function call, no matter how many input elements
       – Only takes values of active elements (e.g., unchecked
         radio buttons or checkboxes are ignored)
       – Giving names to input elements is familiar to HTML
         developers
56
load Example 2: JavaScript
     $(function() {
         $("#params-button-3").click(showParams3);
         $("#params button 3") click(showParams3);
         …
     });

     function showParams3() {
       $("#result2").load("show-params.jsp",
                          $("#form1").serialize());
     }




57




      load Example 2: HTML
     ...
     <fieldset>
       <legend>$.load: Simplifying Params with
                'serialize'</legend>
       <form action="#" id="form1">
              action= # id= form1 >
         param1:
         <input type="text" name="param1"/>
         <br/>
         param2:
         <input type="text" name="param2"/>
         <br/>
          b /
         <input type="button" value="Show Params"
                 id='params-button-3'/>
         <h2 id="result2"></h2>
                            /
       </form>
     </fieldset>
58
load Example 2: JSP
     param1 is ${param.param1},
     param2 is ${param param2}
               ${param.param2}.




            Unchanged from previous examples




59




     load Example 2: Results




60
© 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.




     Approach
     • Server
       – Returns JSON object with no extra parens. E.g.:
          • { cto: "Resig ", ceo: "Gates ", coo: "Ellison" }
     • Code that calls $ ajax
                       $.ajax
       – Specifies dataType of json. E.g.:
          • $.ajax({ url: address, success: handler, dataType: "json" });
               j ({                                       y     j     })
     • Response handler
       – Receives JavaScript data as first argument. No need for
         parsing or “eval”. Must build HTML from result. E.g.:
             i      “ l” M b ild               f        l E
          • function handler(companyExecutives) {
              $("#some-id").html("<b>Chief Technology Officer is " +
                (          )    (                  gy
                                  companyExecutives.cto + "</b>");
            }
62
JSON Example Code: Core
      JavaScript
     $(function() { …
         $( #nums-button ).click(showNums);
         $("#nums-button") click(showNums);
     });

     function showNums() {
       $.ajax({ url: "show-nums",
                dataType: "json",
                success: showNumberList })
                           h N b Li t });
     }                                     Strings


     function showNumberList(jsonData) {
                            (        )
       var list = makeList(jsonData.fg, jsonData.bg,
                           jsonData.fontSize,
                           jsonData.numbers);
       $("#result3").html(list);                           int
                                          Array of doubles
63   }




      JSON 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");
     }

64
JSON 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>");
     }




65




     JSON Example Code: HTML
     <fieldset>
       <legend>$.ajax: T
       <l     d>$ j     Treating R
                            ti   Response as JSON</l
                                             JSON</legend>
                                                        d>
       <form action="#">
          <input type="button" value="Show Nums"
                 id='nums-button'/>
          <div id="result3"></div>
       </form>
     </fieldset>




66
JSON 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);
67
     }}




      JSON 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 jQuery
           eval .
        – Types
           • fg and bg: Strings
           • f tSi
             fontSize: i t
                       int
           • numbers: Array of doubles
68
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}
     }




69




         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)]);
         }
     }

70
JSON Example: Results




71




                                                                                                © 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
73    – Lowest: GWT




      Books and References
     • jQuery in Action
        – by Bear Bibeault, Yehuda Katz, and John Resig
     • Learning jQuery 1.3
        –b J
         by Jonathan Ch ff K l S db
                 h Chaffer, Karl Swedberg, and John R i
                                             d J h Resig
     • http://docs.jquery.com/
        – Very complete
        – Moderately well organized
        – Moderate number of explicit examples
                                p         p
     • jQuery UI 1.6
        – By Dan Wellman
        – Looks good, but jQuery UI is changing rapidly (current
          version is 1.7), so the online docs are perhaps better
74
Summary
     • Assigning event handlers programmatically
       $(function() {
           $("#some-id").click(someFunction);
       });


     • General Ajax requests (data-centric Ajax)
       $.ajax({
       $ j ({ url: "relative-address",
                  l     l i     dd
                success: handlerFunction,
                data: $("#form-id").serialize(),
                dataType: "j
                d t T     "json" })
                               " });


     • Loading result (content-centric Ajax)
       $("#result-id").load("relative-address",
                            $("#form-id").serialize());
75




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

Mais conteúdo relacionado

Mais procurados

Nothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive WebNothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive Webcolinbdclark
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuerycolinbdclark
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupalBlackCatWeb
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuerycolinbdclark
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsBruce Schubert
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsJustin Edelson
 

Mais procurados (13)

Nothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive WebNothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive Web
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
jQuery
jQueryjQuery
jQuery
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 

Semelhante a jQuery Ajax tutorial covers data and content loading

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxtutorialsruby
 
2a-JQuery AJAX.pptx
2a-JQuery AJAX.pptx2a-JQuery AJAX.pptx
2a-JQuery AJAX.pptxLe Hung
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy Sharp
 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneMarius Soutier
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)Doris Chen
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 

Semelhante a jQuery Ajax tutorial covers data and content loading (20)

Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
 
JQuery-Tutorial
 JQuery-Tutorial JQuery-Tutorial
JQuery-Tutorial
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
Json generation
Json generationJson generation
Json generation
 
2a-JQuery AJAX.pptx
2a-JQuery AJAX.pptx2a-JQuery AJAX.pptx
2a-JQuery AJAX.pptx
 
Java script core
Java script coreJava script core
Java script core
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
J query
J queryJ query
J query
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

jQuery Ajax tutorial covers data and content loading

  • 1. © 2009 Marty Hall The jQuery JavaScript Library j y p y Part I: Ajax Support (j (jQuery 1.3 Version) y ) Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/jquery.html p jq y 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 jQuery • Installation and documentation • Quick summary of jQuery selectors • Data centric Ajax: the “$.ajax” function – Basics – O ti Options – Sending data • Content-centric Ajax: the “load” function load • Handling JSON data • Comparing Ajax support to other libraries – Prototype, 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 jQuery • Ajax utilities (this tutorial) – General: $.ajax(…), $(…).load(…) – Shortcuts: $.get, $.post, $.getJSON • DOM search and manipulation utilities – $("p.myStyle").addClass("extraStyle").show(); • Simple animation – Not as extensive as Scriptaculous, but easy to use • Cross-browser event model – A i Assigns h dl programmatically, hides browser differences handlers ti ll hid b diff • General JavaScript utilities – Functions operating on strings and arrays • Rich GUIs 7 – jQuery UI provides widgets, fancier effects, drag/drop Ajax Utilities • $.ajax({options}) – Makes an Ajax request. Example: • $.ajax({ url: "address", success: responseHandler}); • The response handler is passed the response text, not the response object. Don’t forget the “.” before “ajax”! • load(url) – Makes Ajax request and loads result into HTML element k j dl d l i l • $("#some-id").load("address"); • A data string or object is an optional second arg g j p g • Shortcuts – $.get, $.post, $.getJSON • Slightly simpler forms of $.ajax. However, as of jQuery 1.3, they take data objects but not data strings, so you can’t 8 use “serialize”. So, $.ajax is better.
  • 4. Downloading and Installation • Download – http://docs.jquery.com/Downloading_jQuery • Download single minimized file (e.g., jquery-1.3.2.min.js) – Recommend renaming to jquery.js to simplify later upgrades • Online API and tutorials – http://docs.jquery.com/ • Browser Compatibility – Firefox: 2 or later (vs. 1.5 or later for Prototype) – Internet Explorer: 6.0 or later (does not work in IE 5.5) 60 5 5) – Safari: 3.0 or later (vs. 2.0 or later for Prototype) – Opera: 9.0 or later (vs. 9.25 or later for Prototype) – Chrome: 1.0 or later – To check, run the test suite at http://jquery.com/test/ 9 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 jQuery Selectors: Basics Note: brief intro only. More details in next tutorial section. 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. Selecting DOM Elements • Idea – U $(" selector") to get a set of DOM elements Use $("css l ") f l • Then, perform operations on each (see next page) • Much more detail given in next tutorial section • Examples – $("#some-id") • Return 1-element set (or empty set) of element with id 1 element • Simplest use, and most common for Ajax (note the “#”!) – $("p") • Return all p elements – $(".blah") • Return all elements that have class="blah" – $("li b span blah") span.blah") • Return all <span class="blah"> elements that are inside b elements, that in turn are inside li elements 12
  • 6. Manipulating DOM Elements • Common functions on matched elements – $("# $("#some-id").val() id") l() • Returns value of input element. Used on 1-element sets. – $("selector").each(function) • Calls function on each element “this” set to element element. this element. – $("selector").addClass("name") • Adds CSS class name to each. Also removeClass, toggleClass – $("selector") hide() $( selector ).hide() • Makes invisible (display: none). Also show, fadeOut, fadeIn, etc. – $("selector").click(function) • Adds onclick handler Also change focus mouseover etc handler. change, focus, mouseover, etc. – $("selector").html("<tag>some html</tag>") • Sets the innerHTML of each element. Also append, prepend • Chaining – $("a").click(funct1).addClass("name").each(funct2) 13 Example: Randomizing Background Colors (JavaScript) function randomizeHeadings() { Call setRandomStyle function on each h3 element $( h3 ).each(setRandomStyle); $("h3") each(setRandomStyle); $("h3.green").hide("slow"); } Slowly hide every h3 that has CSS style “green” function setRandomStyle() { $(this).addClass(randomStyle()); } Add “red”, “yellow” or “green” CSS names to each function randomStyle() { var sty es = [ ed , "yellow", "green"]; a styles ["red", ye o , g ee ]; return(randomElement(styles)); } function randomElement(array) { ( y) var index = Math.floor(Math.random()*array.length); return(array[index]); 14 }
  • 7. Example: Randomizing Colors (JavaScript Continued) function revertHeadings() { $( h3.green ).show( slow ); $("h3 green") show("slow"); $("h3").removeClass("red").removeClass("yellow") .removeClass("green"); } Like smart window.onload. Explained in next section. $(function() { $("#button1").click(randomizeHeadings); $("#b tt 1") li k( d i H di ) $("#button2").click(revertHeadings); }); Sets onclick handlers 15 Example: Randomizing Colors (Style Sheet) .red { background-color: red } .yellow { background-color: yellow } yellow .green { background-color: green } … Names set by setRandomStyles function 16
  • 8. Example: Randomizing Colors (HTML) … <head><title>jQuery Basics</title> <link rel="stylesheet" href="./css/styles.css" Renamed from jquery-1.3.2.min.js type="text/css"/> <script src="./scripts/jquery.js" type="text/javascript"></script> <script src="./scripts/jquery-basics.js" < i t " / i t /j b i j " type="text/javascript"></script> </head> 17 Example: Randomizing Colors (HTML Continued) … <h3>Foo, bar, <h3>Foo bar baz</h3> <h3>Blah, blah, blah</h3> <h3>Yadda, yadda, yadda</h3> <h3>Foo, bar, <h3>Foo bar baz</h3> <h3>Blah, blah, blah</h3> <h3>Yadda, yadda, yadda</h3> <h3>Foo, b <h3>F bar, b </h3> baz</h3> <h3>Blah, blah, blah</h3> The ids to which click <h3>Yadda, yadda, yadda</h3> handlers were attached. <form action="#"> # <input type="button" id="button1" value="Randomize Headings"/> <input type="button" id="button2" value="Revert Headings"/> 18 </form> …
  • 9. Example: Randomizing Colors (Results) After “Randomize Headings”. Some headings turned green, then gradually disappeared. When page originally loaded, or after “Revert Headings” 19 Understanding Operations on Sets of Elements • Instead of this function randomizeHeadings() { $("h3").each(setRandomStyle); $("h3.green").hide("slow"); $("h3 green") hide("slow"); } function setRandomStyle() { y () $(this).addClass(randomStyle()); } • Why can’t I simply do this? function randomizeHeadings() { $("h3").addClass(randomStyle()) $("h3") ddCl ( d St l ()) $("h3.green").hide("slow"); 20 }
  • 10. © 2009 Marty Hall $.ajax: 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: Basic Syntax • $.ajax(optionsObject) – Minimal form: $.ajax({url: "address", success: funct}); • Don’t forget the “.”. It is $.ajax(…), not $ajax(…). – The handler function gets the response text, not the response object. jQuery figures out if it should be plain text or XML from the response type. If you want the type handler to get JSON, use dataType option • Options for $.ajax({…}) p $ j ({ }) – Almost-always used • url, success – Other common options • cache, data, dataType, error, type, username, password 22
  • 11. 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); } 23 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}); 24
  • 12. $.ajax Example Code: JavaScript function showTime1() { $.ajax({ $ ajax({ url: "show time jsp" "show-time.jsp", success: showAlert, cache: false }); The cache option is not required but is a convenient required, } option when the same URL (including query data) yields different responses. This way, you don’t have to send Cache-Control and Pragma headers from server. function showAlert(text) { alert(text); } This is the response text, not the response object (XmlHttpRequest). Also note that the latest Firefox does not let you pass native functions here, so you cannot use alert instead of showAlert for the success parameter. 25 $.ajax Example Code: HTML ... <head><title>jQuery and Ajax</title>... Ajax</title> <script src="./scripts/jquery.js" type="text/javascript"></script> <script src="./scripts/jquery-ajax.js" src=" /scripts/jquery ajax js" type="text/javascript"></script> </head> <body>... <b d > <fieldset> <legend>$.ajax: Basics (Using onclick handler in HTML)</legend> <form action="#"> <input type="button" value="Show Time" onclick='showTime1()'/> li k ' h Ti 1()'/> </form> 26 </fieldset>
  • 13. $.ajax Example Code: JSP It is now <%= new java.util.Date() %> 27 $.ajax: Results 28
  • 14. Registering Event Handlers in JavaScript • Basic approach – Previous example set the onclick handler in the HTML. Although this is common with some Ajax libraries, jQuery advocates setting it in the JavaScript instead • Often referred to as “unobtrusive JavaScript”: no explicit JavaScript anywhere in the HTML page • jQuery support – $(function() {…}); • Function runs after the DOM is loaded, but does not wait , for images, as with window.onload • Use this approach to set up all event handlers – $("#some-id") click(someHandler); $( #some id ).click(someHandler); • Assigns to onclick handler. Handler is passed an Event object with characteristics that are unified across browsers 29 Redoing Time Alert: JavaScript $(function() { $("#time-button-1").click(showTime1); $("#time button 1") click(showTime1); }); function showTime1() { $.ajax({ url: "show-time.jsp", These two functions success: showAlert, are unchanged from previous example. cache: false }); } function showAlert(text) { alert(text); } 30
  • 15. Redoing Time Alert: HTML <fieldset> <legend>$.ajax: <legend>$ ajax: Basics (Using click function in JavaScript)</legend> <form action="#"> <input type="button" value="Show Time" id='time-button-1'/> </form> </fieldset> 31 Redoing Time Alert: Results Works exactly the same as previous example example. 32
  • 16. © 2009 Marty Hall $.ajax: $ ajax: Sending Data 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. Overview • $.ajax({ url: …, success: …, data: …}); – Can be a String, in which case it is sent unchanged. • On end of URL or in POST data, depending on HTTP type • See later example for building the string automatically using the “serialize” function – Can be an object, in which case query string gets built out of property names and URL-encoded property values URL encoded • Works identically to “parameters” option in Prototype • Equivalent examples q p – $.ajax({… data: "param1=foo+bar%21&param2=baz"}); – $.ajax({… data: { param1: "foo bar!", param2: "baz"}}); 34
  • 17. Data Example: JavaScript $(function() { $("#params-button-1").click(showParams1); $("#params button 1") click(showParams1); … }); function showAlert(text) { alert(text); } Same function used in earlier examples. function showParams1() { () $.ajax({ url: "show-params.jsp", data: "param1=foo&param2=bar", success: showAlert }); } The cache option is not used since the same data always results in the same response. 35 Data Example: HTML … <fieldset> <legend>$.ajax: The 'data' Option</legend> <form action="#"> <input type="button" value="Show Params" id='params-button-1'/> </form> </fieldset> 36
  • 18. Data Example: JSP param1 is ${param.param1}, param2 is ${param param2} ${param.param2}. 37 Data Example: Results 38
  • 19. © 2009 Marty Hall $.ajax: $ ajax: Options and Shortcuts p 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 • Options (almost) always used: url, success – $.ajax({url: "some-address", success: someFunction}); • success is not strictly required; you might want to just fire off some data to the server and not display anything p y y g • Common options: example $.ajax({ url: " dd l "address"," success: successHandlerFunction, data: { param1: "foo bar", param2: "baz"}, error: errorHandlerFunction, cache: false, dataType: "json", yp j , username: "resig", password: "scriptaculous-fan" }); 40
  • 20. Options Name Description Default async Should th Sh ld the request be asynchronous? U synchronous requests with tb h ? Use h t ith true t caution since they lock up the browser. beforeSend Function to modify XMLHttpRequest object before it is sent (e.g., None to set custom headers). The XHR is automatically passed to function. cache Is browser permitted to cache the page? Set to false if you use GET true and you could get different responses back from the same data. (except false if Equivalent to having the server send Cache Control: no cache and Cache-Control: no-cache dataType is script Pragma: no-cache. or json) complete Function to be called after error or success function is finished. None contentType Content-Type of data sent to server. Rarely needed. Content Type application/ pp x-www-form- urlencoded data Data to send to server (possibly after conversion). Sent in the Empty appropriate place depending on whether it is GET or POST. Can be a String or an object. If a String, sent unchanged. If an object, property names become param names and property values get URL- encoded and become param values. & and = inserted automatically. 41 Options (Continued) Name Description Default dataFilter d t Filt Response-data sanitizing function. R l used. R d t iti i f ti Rarely d None N dataType The format in which to pass the response to the handler function. html or xml Legal values are text, html (same as text except embedded scripts (makes intelligent are run), xml, json, jsonp (JSON with Padding), and script ), ,j ,j p( g), p guess) (evaluates the response as JavaScript and returns it as plain text). error Function to be called if request fails. Function is passed 3 args: the None XHR object, a string describing the error type, and an optional exception object. Possible values for the second argument are null, object null "timeout", "error", "notmodified" and "parsererror". global jQuery lets you set global defaults for various handlers: should they true be used if set? ifModified Should the request be considered successful only if the response has false changed since the last request (based on the Last-Modified header)? jsonp Override the callback function name in a jsonp request. JSONP is a callback JSON extension in which the name of a callback function is e tension hich f nction specified as an input argument of the call itself. password Username and password to be used in response to HTTP None 42 username authentication request.
  • 21. Options (Continued) Name Description Default processData D t Should th Sh ld the value of th “data” property, if an object, be turned into l f the “d t ” t bj t b t di t true t a URL-encoded query string? scriptCharset Forces the request to be interpreted as a certain charset. Only for None requests with dataType of “jsonp” or “script” and type of “GET”. success Function to be called if request succeeds. Function gets passed 2 None args: the data returned from the server (formatted according to the dataType property), and a string describing the status. timeout ti t Timeout in milliseconds. If request takes longer, the error handler Ti i illi d k l h h dl Global timeout, if Gl b l ti t will be called instead of the success handler. set via $.ajaxSetup type The HTTP method to use for the request. “get” and “post” are get main options, but some browsers support other methods. i i b b h h d url The address to request. Should be a relative URL. None xhr Callback for creating your own custom XMLHttpRequest object. ActiveXObject if available (IE) (IE), XMLHttpRequest otherwise 43 Shortcuts for $.ajax: Equivalent Forms • $.get – $ (" l" d Obj someFunct) $.get("url", dataObj, F ) – $.ajax({url: "url", data: dataObj, success: someFunct}); • $.post – $.post("url", dataObj, someFunct) – $.ajax({url: "url", data: dataObj, success: someFunct, type: "post"}); post }); • $.getJSON – $.getJSON("url", dataObj, someFunct) g ( , j, ) – $.ajax({url: "url", data: dataObj, success: someFunct, dataType: "json"}); • Note – get and post take the type as an optional fourth argument 44
  • 22. Pros and Cons of Shortcuts • Advantages of shorthand functions – Slightly shorter and (arguably) clearer • Disadvantages of shorthand functions – Th data cannot be a string. This means you cannot use The d b i Thi the serialize function (discussed later) to automatically build the query string from the form q y g – If you want additional options later, you have to change existing code more drastically – If you don’t have data you have to pass in null. This is data, null less convenient than just omitting the “data” property. • $.get("url", null, someHandler); vs. • $.ajax({url: "url", success: someHandler}); 45 © 2009 Marty Hall Simplifying Inserting Results p y g g into HTML: the “load” Function load 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.
  • 23. load: Basic Syntax • Basic forms – $("#result-area-id").load("url"); – $("#result-area-id").load("url", data); – $("#result area id") load("url" data handlerFunction); $("#result-area-id").load("url", data, • Helper utilities – val: reading the value of an input element • var text = $("#some-textfield-id").val(); • Works for all input elements, even multiselectable select elements (in which case it returns an array) – Filtering returned HTML • Add jQuery selectors to the URL. Only elements that match will b i t h ill be inserted. E t d E.g., t i to insert only li elements: t l l t – $("#result-id").load("address li"); 47 – Go very light with filtering: use data-centric Ajax instead. 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 } } 48
  • 24. Content-Centric Ajax with and without Toolkits ($ ajax) ($.ajax) function ajaxResult(address, resultRegion) { $.ajax({ $ ajax({ url: address, success: function(text) { showResponseText(text, showResponseText(text resultRegion); } }); } function showResponseText(text, resultRegion) { $(resultRegion).html(text); $( ) ( ) } Note: use the “html” function (as above) to replace the innerHTML of the element. Use “append” to add to the end of the innerHTML of the element. 49 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 expl licit support for content-centric Ajax f • Ext-JS function ajaxResult(address resultRegion) { ajaxResult(address, Ext.get(resultRegion).load({ url: address}); } 50
  • 25. load Example 1: JavaScript $(function() { $("#params-button-2").click(showParams2); $("#params button 2") click(showParams2); … }); field1 and field2 are textfield ids (not names) function showParams2() { var params = { param1: $("#field1").val(), param2: $("#field2").val() }; $( # $("#result1").load("show-params.jsp", params); ) ( p j p , p ); } id of div whose innerHTML will become the result text. 51 load Example 1: HTML ... <fieldset> <legend>$.load: Simplifying HTML Insertion</legend> <form action="#"> param1: <input type="text" id="field1"/> <br/> param2: <input type="text" id="field2"/> <br/> / <input type="button" value="Show Params" id="params-button-2"/> <h2 id="result1"></h2> id= result1 ></h2> </form> </fieldset> 52
  • 26. load Example 1: JSP param1 is ${param.param1}, param2 is ${param param2} ${param.param2}. Unchanged from previous example 53 load Example 1: Results 54
  • 27. © 2009 Marty Hall Building Parameter Strings Automatically with “serialize” 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. Using “serialize” • Idea – You specify a form, and jQuery automatically builds query string from all appropriate input elements. – The element names (not ids) become the param names • Syntax – $("result-id").load("url", $("#form-id").serialize()); $( ) ( , $( ) ()); • Advantages – One function call, no matter how many input elements – Only takes values of active elements (e.g., unchecked radio buttons or checkboxes are ignored) – Giving names to input elements is familiar to HTML developers 56
  • 28. load Example 2: JavaScript $(function() { $("#params-button-3").click(showParams3); $("#params button 3") click(showParams3); … }); function showParams3() { $("#result2").load("show-params.jsp", $("#form1").serialize()); } 57 load Example 2: HTML ... <fieldset> <legend>$.load: Simplifying Params with 'serialize'</legend> <form action="#" id="form1"> action= # id= form1 > param1: <input type="text" name="param1"/> <br/> param2: <input type="text" name="param2"/> <br/> b / <input type="button" value="Show Params" id='params-button-3'/> <h2 id="result2"></h2> / </form> </fieldset> 58
  • 29. load Example 2: JSP param1 is ${param.param1}, param2 is ${param param2} ${param.param2}. Unchanged from previous examples 59 load Example 2: Results 60
  • 30. © 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. Approach • Server – Returns JSON object with no extra parens. E.g.: • { cto: "Resig ", ceo: "Gates ", coo: "Ellison" } • Code that calls $ ajax $.ajax – Specifies dataType of json. E.g.: • $.ajax({ url: address, success: handler, dataType: "json" }); j ({ y j }) • Response handler – Receives JavaScript data as first argument. No need for parsing or “eval”. Must build HTML from result. E.g.: i “ l” M b ild f l E • function handler(companyExecutives) { $("#some-id").html("<b>Chief Technology Officer is " + ( ) ( gy companyExecutives.cto + "</b>"); } 62
  • 31. JSON Example Code: Core JavaScript $(function() { … $( #nums-button ).click(showNums); $("#nums-button") click(showNums); }); function showNums() { $.ajax({ url: "show-nums", dataType: "json", success: showNumberList }) h N b Li t }); } Strings function showNumberList(jsonData) { ( ) var list = makeList(jsonData.fg, jsonData.bg, jsonData.fontSize, jsonData.numbers); $("#result3").html(list); int Array of doubles 63 } JSON 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"); } 64
  • 32. JSON 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>"); } 65 JSON Example Code: HTML <fieldset> <legend>$.ajax: T <l d>$ j Treating R ti Response as JSON</l JSON</legend> d> <form action="#"> <input type="button" value="Show Nums" id='nums-button'/> <div id="result3"></div> </form> </fieldset> 66
  • 33. JSON 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); 67 }} JSON 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 jQuery eval . – Types • fg and bg: Strings • f tSi fontSize: i t int • numbers: Array of doubles 68
  • 34. 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} } 69 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)]); } } 70
  • 35. JSON Example: Results 71 © 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.
  • 36. “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 73 – Lowest: GWT Books and References • jQuery in Action – by Bear Bibeault, Yehuda Katz, and John Resig • Learning jQuery 1.3 –b J by Jonathan Ch ff K l S db h Chaffer, Karl Swedberg, and John R i d J h Resig • http://docs.jquery.com/ – Very complete – Moderately well organized – Moderate number of explicit examples p p • jQuery UI 1.6 – By Dan Wellman – Looks good, but jQuery UI is changing rapidly (current version is 1.7), so the online docs are perhaps better 74
  • 37. Summary • Assigning event handlers programmatically $(function() { $("#some-id").click(someFunction); }); • General Ajax requests (data-centric Ajax) $.ajax({ $ j ({ url: "relative-address", l l i dd success: handlerFunction, data: $("#form-id").serialize(), dataType: "j d t T "json" }) " }); • Loading result (content-centric Ajax) $("#result-id").load("relative-address", $("#form-id").serialize()); 75 © 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.