Upload
arupghosh88
View
241
Download
0
Embed Size (px)
Citation preview
8/9/2019 jQuery Javascript Library Part I Ajax Support
1/36
2009 Marty Hall
The Quer JavaScri t LibrarPart I: Ajax Support
( Quer 1.3 Version)
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/ajax.html
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2009 Marty Hall
For l ive Ajax & GWT training, see trainingcourses a p: courses.coreserv e s.com .Taught by the author ofCore Servlets and JSP, More
, .venues, or customized versions can be held on-site
at your organization.
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Courses developed and taught by Marty HallJava 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Courses developed and taught by coreservlets.com experts (edited by Marty)Spring, Hibernate/JPA, EJB3, Ruby/Rails
Contact [email protected] for details
8/9/2019 jQuery Javascript Library Part I Ajax Support
2/36
Topics in This Section
Overview of jQuery
Installation and documentation
Quick summary of jQuery selectors Data centric Ajax: the ajax function
Basics
pt ons
Sending data
-
Handling JSON data
5
2009 Marty Hall
Introduction
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
3/36
Overview of jQuery
Ajax Utilities General: $.ajax(), $().load()
Shortcuts: $.get, $.post, $.getJSON
$("p.myStyle").addClass("extraStyle").show();
Simple animation Not as extensive as Scriptaculous, but easy to use
Cross-browser event model ss gn an ers programmat ca y, es rowser erences
General JavaScript utilities
Rich GUIs jQuery UI provides widgets, fancier effects, drag/drop
7
Ajax Utilities
$.ajax({options}) Makes an Ajax request. Example:
$.ajax({ url: "address", success: responseHandler});
The res onse handler is assed the res onse text not theresponse object. Dont forget the . before ajax!
load(url) Makes Ajax request and loads result into HTML element $("#some-id").load("address");
A data string or object is an optional second arg
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 cantuse serialize. So, $.ajax is better.
8
8/9/2019 jQuery Javascript Library Part I Ajax Support
4/36
Downloading and Installation
Download http://docs.jquery.com/Downloading_jQuery
Download single minimized file (e.g., jquery-1.3.2.min.js) Recommend renamin to uer . s to sim lif later u rades
Online API and tutorials http://docs.jquery.com/
Browser Compatibility Firefox: 2 or later (vs. 1.5 or later for Prototype) . . 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
10
Approximately 40% of matches to prototype and JavaScript were false positives such as build a
prototype wit h JavaScript. So, discount t he Prototype graph by about 40%.
8/9/2019 jQuery Javascript Library Part I Ajax Support
5/36
2009 Marty Hall
Basics
Note: brief intro only. More details in next tutorial section.
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Selecting DOM Elements
Idea se css se ector to get a set o e ements
Then, perform operations on each (see next page) Much more detail given in next tutorial section
Examples $("#some-id")
- Simplest use, and most common for Ajax (note the #!)
$("p")
$(".blah") Return all elements that have class="blah"
" " . Return all elements that are inside b
elements, that in turn are inside li elements12
8/9/2019 jQuery Javascript Library Part I Ajax Support
6/36
Manipulating DOM Elements
Common functions on matched elements" " some- .va
Returns value of input element. Used on 1-element sets.
$("selector").each(function) . .
$("selector").addClass("name") Adds CSS class name to each. Also removeClass, toggleClass
" " . Makes invisible (display: none). Also show, fadeOut, fadeIn, etc.
$("selector").click(function) . , , , .
$("selector").html("some html")
Sets the innerHTML of each element. Also append, prepend
$("a").click(funct1).addClass("name").each(funct2)
13
Example: Randomizing
function randomizeHeadings() {
" "
Call setRandomStyle function on each h3 element
.
$("h3.green").hide("slow");
} Slowly hide every h3 that has CSS style green
function setRandomStyle() {
$(this).addClass(randomStyle());
function randomStyle() {
Add red , yellow or green CSS names to each
var d = Math.random();
if (d < 1.0/3) { return("red"); }
if (d < 2.0/3) { return("yellow"); }
return("green");
}
14
8/9/2019 jQuery Javascript Library Part I Ajax Support
7/36
Example: Randomizing Colors
function revertHeadings() {
" " " ". .
$("h3").removeClass("red").removeClass("yellow")
.removeClass("green");
$(function() {
Like smart w indow.onload. Explained in next section.
" utton " .c c ran om zeHea ngs ;
$("#button2").click(revertHeadings);
});
Sets onclick handlers
15
Example: Randomizing Colors
.red { background-color: red }
. -
.green { background-color: green }
Names set by setRandomStyles function
16
8/9/2019 jQuery Javascript Library Part I Ajax Support
8/36
Example: Randomizing Colors
oo, ar, az< >
Blah, blah, blah
Yadda, yadda, yaddaThe ids to which click
handlers were attached.
18
8/9/2019 jQuery Javascript Library Part I Ajax Support
9/36
Example: Randomizing Colors
After Randomize Headings. Some headings turned
green, then gradually disappeared.
19When page originally loaded, or after Revert Headings
2009 Marty Hall
.ajax: Basics
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
10/36
$.ajax: Basic Syntax
$.ajax(optionsObject) Minimal form: $.ajax({url: "address", success: funct});
Dont forget the .. It is $.ajax(), not $ajax(). ,
response object. jQuery figures out if it should be plaintext or XML from the response type. If you want the
an er o ge , use a a ype op on
Options for $.ajax({}) -
url, success
Other common options cache, data, dataType, error, type, username, password
21
Ajax with and without Toolkits
With basic JavaScriptfunction 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);
}
22
8/9/2019 jQuery Javascript Library Part I Ajax Support
11/36
Ajax with and without Toolkits
Prototype (handler passed response object)new Ajax.Request("address",
{onSuccess: handlerFunct});
$.ajax({url: "address",
success: handlerFunct});
Dojo (handler passed response text)dojo.xhrGet({url: "address",
load: handlerFunct
23
$.ajax Example Code:
function showTime1() {
. - . ,
success: showAlert,
cache: false });}
function showAlert(text) {
,
option when the same URL (including query data) yieldsdifferent responses. This way, you dont have to send
Cache-Control and Pragma headers from server.
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 youcannot use alert instead of showAlert for the success
parameter.
24
8/9/2019 jQuery Javascript Library Part I Ajax Support
12/36
$.ajax Example Code:
...
...
scr p src= . scr p s query-a ax. s
type="text/javascript">
< o y>...
$.ajax: Basics (Using onclickan er n < egen >
25
$.ajax Example Code:
It is now
26
8/9/2019 jQuery Javascript Library Part I Ajax Support
13/36
$.ajax: Results
27
Registering Event Handlers in
Basic approach Previous example set the onclick handler in the HTML.
Although this is common with other Ajax libraries,uer advocates settin it in the JavaScri t instead
Often referred to as unobtrusive JavaScript: no explicitJavaScript anywhere in the HTML page
$(function() {});
Function runs after the DOM is loaded, but does not waitfor images, as with window.onload
Use this approach to set up allevent handlers
" - " . Assigns to onclick handler. Handler is passed an Event
object with characteristics that are unified across browsers28
8/9/2019 jQuery Javascript Library Part I Ajax Support
14/36
Redoing Time Alert: JavaScript
$(function() {
- - .
});
function showTime1() {
$.ajax({ url: "show-time.jsp",These two functions
success: showAlert,
cache: false });
are unchanged from
previous example.
function showAlert(text) {
}
29
Redoing Time Alert: HTML
.
function in JavaScript)
30
8/9/2019 jQuery Javascript Library Part I Ajax Support
15/36
Redoing Time Alert: Results
31
.
2009 Marty Hall
.Sendin Data
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
16/36
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
using the serialize function
Can be an object, in which case query string gets built out-
Works identically to parameters option in Prototype
E uivalent exam les $.ajax({ data: "param1=foo+bar%21¶m2=baz"});
$.ajax({ data: { param1: "foo bar!", param2: "baz"}});
33
Data Example: JavaScript
$(function() {
- - .
});
function showAlert(text) {
alert(text);}
function showParams1
Same function used in earlier examples.
$.ajax({ url: "show-params.jsp",
data: "param1=foo¶m2=bar",
}
34
The cache option is not used since the same data always
results in the same response.
8/9/2019 jQuery Javascript Library Part I Ajax Support
17/36
Data Example: HTML
$.ajax: The 'data' Option
35
Data Example: JSP
param1 is ${param.param1},
. .
36
8/9/2019 jQuery Javascript Library Part I Ajax Support
18/36
Data Example: Results
37
2009 Marty Hall
.O tions and Shortcuts
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
19/36
Overview
Options (almost) always used: url, success $.ajax({url: "some-address", success: someFunction});
success is not strictly required; you might want to just fireoff some data to the server and not dis la an thin
Common options: example$.ajax({
url: "address",
success: successHandlerFunction,
data: { param1: "foo bar", param2: "baz"},
error: errorHandlerFunction,
cache: false,
dataT e: " son",
username: "resig",
password: "scriptaculous-fan" });39
OptionsName Description Default
async ou t e request e async ronous se sync ronous requests w tcaution since they lock up the browser.
rue
beforeSend Function to modify XMLHttpRequest object before it is sent (e.g.,to set custom headers). The XHR is automatically passed to
None
function.
cache Is browser permitted to cache the page? Set to false if you use GETand you could get different responses back from the same data.
- -
true(except false if
dataT e is scri t
Pragma: no-cache.
or json)
complete Function to be called after error or success function is finished. None
Content-T e of data sent to server. Rarel needed. application/x-www-form-urlencoded
data Data to send to server (possibly after conversion). Sent in thea ro riate lace de endin on whether it is GET or POST. Can be
Empty
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.40
8/9/2019 jQuery Javascript Library Part I Ajax Support
20/36
Options (Continued)
Name Description Default
ata ter esponse- ata san t z ng unct on. are y use . one
dataType The format in which to pass the response to the handler function.Legal values are text, html (same as text except embedded scripts
are run), xml, json, jsonp (JSON with Padding), and script
html or xml(makes intelligent
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: theXHR object, a string describing the error type, and an optional
None
. ,
"timeout", "error", "notmodified" and "parsererror".
global jQuery lets you set global defaults for various handlers: should theybe used if set?
true
ifModified Should the request be considered successful only if the response haschanged since the last request (based on the Last-Modified header)?
false
jsonp Override the callback function name in a jsonp request. JSONP is a callbackextens on n w c t e name o a ca ac unct on s
specified as an input argument of the call itself.
passwordusername
Username and password to be used in response to HTTP
authentication request.None
41
Options (Continued)Name Description Default
process a a ou t e va ue o t e ata p roperty, an o ect, e turne ntoa URL-encoded query string?
rue
scriptCharset Forces the request to be interpreted as a certain charset. Only forrequests with dataType of jsonp or script and type of GET.
None
success Function to be called if request succeeds. Function gets passed 2args: the data returned from the server (formatted according to the
dataType property), and a string describing the status.
None
t meout Timeout in milliseconds. If request takes longer, the error handlerwill be called instead of the success handler.
o a meou,set via
$.ajaxSetup
type The HTTP method to use for the request. get and post are getmain options, but some browsers support other methods.
url The address to request. Should be a relative URL. None
xhr Callback for creating your own custom XMLHttpRequest object. ActiveXObject if,
XMLHttpRequestotherwise
42
8/9/2019 jQuery Javascript Library Part I Ajax Support
21/36
Shortcuts for $.ajax:
$.get .get ur , ata , some unct
$.ajax({url: "url", data: dataObj, success: someFunct}); . ost
$.post("url", dataObj, someFunct) $.ajax({url: "url", data: dataObj, success: someFunct,
" "
$.getJSON $.get("url", dataObj, someFunct) $.ajax({url: "url", data: dataObj, success: someFunct,
dataType: "json"}); get and post take the type as an optional fourth argument
43
Pros and Cons of Shortcuts
Advantages of shorthand functions Slightly shorter and (arguably) clearer
Disadvantages of shorthand functions e ata cannot e a str ng. s means you cannot use
the serialize function (discussed later) to automatically
build the query string from the form If you want additional options later, you have to change
existing code more drastically
, .less convenient than just omitting the data property.
$.get("url", null, someHandler); vs.
$.ajax({url: "url", success: someHandler});
44
8/9/2019 jQuery Javascript Library Part I Ajax Support
22/36
2009 Marty Hall
Sim lif in Insertin Resultsinto HTML:
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
load: Basic Syntax
Basic forms $("#result-area-id").load("url");
$("#result-area-id").load("url", data);
" " " " - - . , ,
Helper utilities
var text = $("#some-textfield-id").val();
Works for all input elements, even multiselectable select
Filtering returned HTML Add jQuery selectors to the URL. Only elements that
matc w e nserte . .g., to nsert on y e ements: $("#result-id").load("address li");
Go very light with filtering: use data-centric Ajax instead.46
8/9/2019 jQuery Javascript Library Part I Ajax Support
23/36
Ajax with Result Insertion:
function getRequestObject() { ... }
function ajaxResult(address, resultRegion) {
var request = getRequestObject();request.onreadystatechange =function() { showResponseText(request,
resultRegion); };request.open("GET", address, true);
.}
function showResponseText(request, resultRegion) {if ((request.readyState == 4) &&
(request.status == 200)) {
document.getElementById(resultRegion).innerHTML =request.responseText;
}}
47
Ajax with Result Insertion: $.ajax
function ajaxResult(address, resultRegion) {
url: address,
success: function(text) {
s ow esponse ex ex , resu eg on ;
}
});
function showResponseText(text, resultRegion) {
(resultRegion).html(text);
}
48
Note: use the html function (as above) to replace the
innerHTML of the element. Use append to add to theend of the innerHTML of the element.
8/9/2019 jQuery Javascript Library Part I Ajax Support
24/36
Ajax with Result Insertion: load
function ajaxResult(address, resultRegion) {
resu eg on . oa a ress ;
}
Comparison to Prototype In Prototype, it would be the following
function ajaxResult(address, resultRegion) {
new Ajax.Updater(resultRegion, address);
}49
load Example 1: JavaScript
$(function() {
- - .
}); param1 and param2 are textfield ids (not names)
function showParams2() {
var params ={ param1: $("#param1").val(),
param2: $("#param2").val() };
$ "#result1" .load "show- arams. s " arams
}
50
id of div whose innerHTML will become the result text.
8/9/2019 jQuery Javascript Library Part I Ajax Support
25/36
load Example 1: HTML
...
$.load: Simplifying HTML Insertion
51
load Example 1: JSP
param1 is ${param.param1},
. .
Unchanged from previous example
52
8/9/2019 jQuery Javascript Library Part I Ajax Support
26/36
load Example 1: Results
53
2009 Marty Hall
Automatically with serialize
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
27/36
Using serialize
Idea You specify a form, and jQuery automatically builds
query string from all appropriate input elements.
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)
developers
55
load Example 2: JavaScript
$(function() {
- - .
});
function showParams3() {
$("#result2").load("show-params.jsp",$("#form1").serialize());
}
56
8/9/2019 jQuery Javascript Library Part I Ajax Support
28/36
load Example 2: HTML
...
$.load: Simplifying Params with
'serialize'< =" " =" ">
param1:
< >
param2:
57
load Example 2: JSP
param1 is ${param.param1},
. .
Unchanged from previous examples
58
8/9/2019 jQuery Javascript Library Part I Ajax Support
29/36
load Example 2: Results
59
2009 Marty Hall
an ng a a
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
30/36
Approach
Server Returns JSON object with no extra parens. E.g.:
{ cto: "Resig ", ceo: "Gates ", coo: "Ellison" }.
Specifies dataType of json. E.g.: $.ajax({ url: address, success: handler, dataType: "json" });
Response handler Receives JavaScript data as first argument. No need for
pars ng or eva . ust u rom resu t. .g.:
function handler(companyExecutives) {$("#some-id").html("Chief Technology Officer is " +
companyExecutives.cto + "");}
61
JSON Example Code: Core
$(function() {
" "- .
});
unc on s ow ums
$.ajax({ url: "show-nums",
dataType: "json",
success: s ow um er s ;
} Strings
function showNumberList(jsonData) {
var list = makeList(jsonData.fg, jsonData.bg,
jsonData.fontSize,
jsonData.numbers);
$("#result3").html(list);
}62
int
Array of doubles
8/9/2019 jQuery Javascript Library Part I Ajax Support
31/36
JSON Example Code: Auxiliary
function makeList(fg, bg, fontSize, nums) {
listStartTags(fg, bg, fontSize) +
listItems(nums) +
s n ags ;
}
unct on stStartTags g, g, ontS ze
return(
"\n" +
"\n");}
63
JSON Example Code: Auxiliary
function listItems(items) {
""
for(var i=0; i
8/9/2019 jQuery Javascript Library Part I Ajax Support
32/36
JSON Example Code: HTML
< egen > .a ax: rea ng esponse as < egen >
< >
65
JSON Example Code: Servletpublic 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");String fg = ColorUtils.randomColor();request.setAttribute("fg", fg);String bg = ColorUtils.randomColor();
re uest.setAttribute "b " bString fontSize = "" + (10 + ColorUtils.randomInt(30));request.setAttribute("fontSize", fontSize);double[] nums =
. , . , .request.setAttribute("nums", nums);response.setContentType("application/json");String outputPage = "/WEB-INF/results/show-nums.jsp";
request.getRequestDispatcher(outputPage);
dispatcher.include(request, response);}}
66
8/9/2019 jQuery Javascript Library Part I Ajax Support
33/36
JSON Example Code: JSP
{ fg: "${fg}",
bg: " { g}",
fontSize: ${fontSize},numbers: [ ${nums[0]}, ${nums[1]}, ${nums[2]}]
}
o es No enclosing parens. jQuery will wrap in parens and then
ass to eval
Types
fg and bg: Strings on ze: n
numbers: Array of doubles
67
JSON Example Code: Auxiliary
public class ColorUtils {rivate static Strin colors ="aqua", "black", "blue", "fuchsia", "gray","green", "lime", "maroon", "navy", "olive","purple", "red", "silver", "teal", "white", "yellow"
/** A random number between 0 and range-1, inclusive. */
public static int randomInt(int range) {return(new Random().nextInt(range));
}
/** One of the official HTML color names, at random. */
public static String randomColor() {return(colors[randomInt(colors.length)]);
}}
68
8/9/2019 jQuery Javascript Library Part I Ajax Support
34/36
JSON Example: Results
69
2009 Marty Hall
Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
8/9/2019 jQuery Javascript Library Part I Ajax Support
35/36
Comparing Prototype and
Ajax libraries About the same
DOM manipulation facilities uery muc etter
CSS facilities
OOP facilities
Function and array facilities Protot e better
Usage in industry Similar, but jQuery has been growing faster
71
Books and References
jQuery in Action by Bear Bibeault, Yehuda Katz, and John Resig
Learning jQuery 1.3 y onat an a er, ar we erg, an o n es g
http://docs.jquery.com/
Moderately well organized
Moderate number of ex licit exam les
jQuery UI 1.6 By Dan Wellman
Looks good, but jQuery UI is changing rapidly (currentversion is 1.7), so the online docs are perhaps better
72
8/9/2019 jQuery Javascript Library Part I Ajax Support
36/36
Summary
Assigning event handlers programmatically$(function() {
$("#some-id").click(someFunction);});
General Ajax requests (data-centric Ajax)$.ajax({ url: "relative-address",
success: handlerFunction,
data: $("#form-id").serialize(),
a a ype: son ;
$("#result-id").load("relative-address",
$("#form-id").serialize());73
2009 Marty Hall
Questions?