Sei sulla pagina 1di 19

http://docs.jquery.

com/Tutorials:Getting_Started_with_jQuery

Tutorials:Getting Started with jQuery


Setup
To start, we need a copy of the jQuery li rary, which we can get from the main download page. The jQuery Starter!it pro"ides some mar!up and #SS to wor! with. $fter downloading and e%tracting its content we put jquery.js into the same directory and open starter!it.html and custom.js with our fa"orite editor and starter!it.html with a rowser. &ow we ha"e e"erything to start with the notorious '(ello world' e%ample.

Hello jQuery
)e start with an empty html page:
<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // we will add our javascript code here </script> </head> <body> <!-- we will add our H !" co#te#t here --> </body> </html>

This page just loads the jquery.js li rary *ma!e sure the +,- points to where you stored your copy of jquery. This e%ample assumes that you store it in the same directory as this e%ample file/. Two comments indicate where we will e%pand this template with code. $s almost e"erything we do when using jQuery reads or manipulates the document o ject model *012/, we need to ma!e sure that we start adding e"ents etc. as soon as the 012 is ready. To do this, we register a ready e"ent for the document.
$%docume#t&.ready%'u#ctio#%& ( // do stu'' whe# )*! is ready +&,

3utting an alert into that function does not ma!e much sense, as an alert does not require the 012 to e loaded. So lets try something a little more sophisticated: Show an alert when clic!ing a lin!. $dd the following to the <body>:
<a hre'="">"i#-</a>

45678989:.doc / 5

&ow update the $(document).ready handler:


$%docume#t&.ready%'u#ctio#%& ( $%"a"&.clic-%'u#ctio#%& ( alert%"Hello world!"&, +&, +&,

This should show the alert as soon as you clic! on the lin!. -ets ha"e a loo! at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery 'class', therefore $() constructs a new jQuery o ject. The click() function we call ne%t is a method of the jQuery o ject. ;t inds a clic! e"ent to all selected elements *in this case, a single anchor element/ and e%ecutes the pro"ided function when the e"ent occurs. This is similar to the following code:
<a hre'="" o#clic-="alert%.Hello world.&">"i#-</a>

The difference is quite o "ious: )e don<t need to write an onclic! for e"ery single element. )e ha"e a clean separation of structure *(T2-/ and eha"ior *=S/, just as we separate structure and presentation y using #SS. )ith this in mind, we e%plore selectors and e"ents a little further. Interesting links for this section:

jQuery >ase jQuery ?%pressions jQuery >asic ?"ents

Find me: Using selectors and events


jQuery pro"ides two approaches to select elements. The first uses a com ination of #SS and @3ath selectors passed as a string to the jQuery constructor *eg. $("div > ul a")/. The second uses se"eral methods of the jQuery o ject. >oth approaches can e com ined. To try some of these selectors, we select and modify the first ordered list in our starter!it. To get started, we want to select the list itself. The list has an ;0 'orderedlist'. ;n classic =a"aScript, you could select it y using document.getElementById("orderedlist"). )ith jQuery, we do it li!e this:
$%docume#t&.ready%'u#ctio#%& ( $%"/orderedlist"&.add0lass%"red"&, +&,

45678989:.doc / 4

The starter!it pro"ides a stylesheet with a class 'red' that simply adds a red ac!ground. Therefore, when you reload the page in your rowser, you should see that the first ordered list has a red ac!ground. The second list is not modified. &ow lets add some more classes to the child elements of this list.
$%docume#t&.ready%'u#ctio#%& ( $%"/orderedlist > li"&.add0lass%"blue"&, +&,

This selects all child lis of the element with the id orderedlist and adds the class ' lue'. &ow for something a little more sophisticated: )e want to add and remo"e the class when the user ho"ers the li element, ut only on the last element in the list.
$%docume#t&.ready%'u#ctio#%& ( $%"/orderedlist li1last"&.hover%'u#ctio#%& ( $%this&.add0lass%"2ree#"&, +3'u#ctio#%&( $%this&.remove0lass%"2ree#"&, +&, +&,

There are many other selectors similar to #SS and @3ath synta%. 2ore e%amples and a list of all a"aila le e%pressions can e found here. Aor e"ery on%%% e"ent a"aila le, li!e onclic!, onchange, onsu mit, there is a jQuery equi"alent. Some other e"ents, li!e ready and ho"er, are pro"ided as con"enient methods for certain tas!s. Bou can find a complete list of all e"ents in the jQuery ?"ents 0ocumentation. )ith those selectors and e"ents you can already do a lot of things, ut there is more.
$%docume#t&.ready%'u#ctio#%& ( $%"/orderedlist"&.'i#d%"li"&.each%'u#ctio#%i& ( $%this&.appe#d% " 45!! " 6 i &, +&, +&, find() allows you to further search the descendants of the already selected elements, ("#orderedlist").find("li") is mostly the same as $("#orderedlist li"). eac () eac ()

therefore $

iterates o"er e"ery element and allows further processing. 2ost methods, li!e add!lass(), use themsel"es.

;n this e%ample, a""end() is used to append some te%t to it and set it as te%t to the end of each element. $nother tas! you often face is to call methods on 012 elements that are not co"ered y jQuery. Thin! of a form you would li!e to reset after you su mitted it successfully "ia $=$@. 45678989:.doc / C

$%docume#t&.ready%'u#ctio#%& ( // use this to reset a si#2le 'orm $%"/reset"&.clic-%'u#ctio#%& ( $%"'orm"&789.reset%&, +&, +&,

This code selects the first form element and calls reset() on it. ;n case you had more than one form, you could also do this:
$%docume#t&.ready%'u#ctio#%& ( // use this to reset several 'orms at o#ce $%"/reset"&.clic-%'u#ctio#%& ( $%"'orm"&.each%'u#ctio#%& ( this.reset%&, +&, +&, +&,

This would select all forms within your document, iterate o"er them and call reset() for each. &ote that in an .eac () function, t is refers to the actual element. $lso note that, since the reset() function elongs to the form element and not to the jQuery o ject, we cannot simply call $ ("form").reset() to reset all the forms on the page. $n additional challenge is to select only certain elements from a group of similar or identical ones. jQuery pro"ides filter() and not() for this. )hile filter() reduces the selection to the elements that fit the filter e%pression, not() does the contrary and remo"es all elements that fit the e%pression. Thin! of an unordered list where you want to select all li elements that ha"e no ul children.
$%docume#t&.ready%'u#ctio#%& ( $%"li"&.#ot%"1has%ul&"&.css%"border"3 ":px solid blac-"&, +&,

This selects all li elements that ha"e a ul element as a child and remo"es all elements from the selection. Therefore all li elements get a order, e%cept the one that has a child ul. The #e$"ression% synta% is ta!en from @3ath and can e used to filter y attri utes. 2ay e you want to select all anchors that ha"e a name attri ute:
$%docume#t&.ready%'u#ctio#%& ( $%"a7#ame9"&.css%"bac-2rou#d"3 "/eee" &, +&,

This adds a ac!ground color to all anchor elements with a name attri ute. 2ore often than selecting anchors y name, you might need to select anchors y their 'href' attri ute. This can e a pro lem as rowsers eha"e quite inconsistently when returning what they thin! the 'href' "alue is *&ote: This pro lem was fi%ed recently in jQuery, a"aila le in any "ersions after 5.5.5/. To match only a part of the "alue, we can use the contains select 'DE' instead of an equals *'E'/:

45678989:.doc / F

$%docume#t&.ready%'u#ctio#%& ( $%"a7hre';=/co#te#t/2allery9"&.clic-%'u#ctio#%& ( // do somethi#2 with all li#-s that poi#t somewhere to /co#te#t/2allery +&, +&,

+ntil now, all selectors were used to select children or filter the current selection. There are situations where you need to select the pre"ious or ne%t elements, !nown as si lings. Thin! of a A$Q page, where all answers are hidden first, and shown, when the question is clic!ed. The jQuery code for this:
$%docume#t&.ready%'u#ctio#%& ( $%./'aq.&.'i#d%.dd.&.hide%&.e#d%&.'i#d%.dt.&.clic-%'u#ctio#%& ( $%this&.#ext%&.slide o22le%&, +&, +&,

(ere we use some chaining to reduce the code siGe and gain etter performance, as <Hfaq< is only selected once. >y using end(), the first find() is undone, so we can start search with the ne%t find() at our Hfaq element, instead of the dd children. )ithin the clic! handler, the function passed to the click() method, we use I*this/.ne%t*/ to find the ne%t si ling starting from the current dt. This allows us to quic!ly select the answer following the clic!ed question. ;n addition to si lings, you can also select parent elements *also !nown as ancestors for those more familiar with @3ath/. 2ay e you want to highlight the paragraph that is the parent of the lin! the user ho"ers. Try this:
$%docume#t&.ready%'u#ctio#%&( $%"a"&.hover%'u#ctio#%&( $%this&.pare#ts%"p"&.add0lass%"hi2hli2ht"&, +3'u#ctio#%&( $%this&.pare#ts%"p"&.remove0lass%"hi2hli2ht"&, +&, +&,

Aor all ho"ered anchor elements, the parent paragraph is searched and a class 'highlight' added and remo"ed. -ets go one step ac! efore continuing: jQuery is a lot a out ma!ing code shorter and therefore easier to read and maintain. The following is a shortcut for the I*document/.ready*call ac!/ notation:
$%'u#ctio#%& ( // code to execute whe# the )*! is ready +&,

45678989:.doc / 7

$pplied to the (ello world. e%ample, we end with this:


$%'u#ctio#%& ( $%"a"&.clic-%'u#ctio#%& ( alert%"Hello world!"&, +&, +&,

&ow, with the asics at hand, we want to e%plore some other aspects, starting with $=$@. Interesting links for this chapter:

jQuery $3; documentation Jisual jQuery K $ categoriGed rowsa le $3; documentation. jQuery Selectors jQuery ?"ents jQuery 012 Tra"ersing

45678989:.doc / 9

API/1 1 !/"#$/Tra%ersing/Selectors
jQuery selectors are a com ination of #SS 5KC, @3ath, plus some custom code to glue it together. ?ssentially, the est parts from oth of these query languages were ta!en, com ined, and used to create the final jQuery e%pression language. ;f you already !now #SS *which most we de"elopers do/ then you<re going to e fine. ;f you are unsure a out the general differences etween the techniques discussed here, these articles in the ?nglish )i!ipedia may help clarify a lot: @3ath and L

Using CSS and XPath Together


This is a point of confusion, for some: (ow can you use #SS and @3ath together, they<re so different. jQuery ma!es some allowances to ma!e this happen, ut we thin! that de"elopers will really appreciate the ad"antages of each language. (ere are some e%amples: (ide all 3aragraph elements that contain a class attri ute:
$(""#&class%"). ide()'

Show the first paragraph on the page:


$(""(e)(*)").s o+()'

(ide all di"s that are currently showing:


$("div(visible"). ide()'

Get all list items that are children of an unordered list:


$("ul,li") ,- valid too( $("ul > li") -,

Get all 3aragraphs, with a class of <foo<, that ha"e a lin! in them:
$("".foo#a%")'

Get list item that contains lin! with ',egister' te%t inside:
$("li#a(contains(./egister.)%")'

Get the input field<s "alue with the name of < ar<:
$("in"ut#&name0bar%").val()'

$ll chec!ed radio uttons:


$("in"ut#&ty"e0radio%#&c ecked%")

;f you still ha"e questions concerning how this selector language wor!s, please feel free to post to the mailing list.

45678989:.doc / 8

CSS Selectors
jQuery has full #SS 5K4 support and partial #SS C support, along with some custom #SSKli!e functionality *and @3ath/, as part of its e%pression. Aor info on how #SS wor!s feel free to read the "arious lin!s: #SS 5 #SS 4 #SS C )hat follows is a list of supported #SS Selector e%pressions.

& any element ' an element of type ? ':nth(child)n* an ? element, the nKth child of its parent ':first(child an ? element, first child of its parent ':last(child an ? element, last child of its parent ':only(child an ? element, only child of its parent ':e+pty an ? element that has no children *including te%t nodes/ ':ena,led a user interface element ? which is not disa led ':disa,led a user interface element ? which is disa led ':checked a user interface element ? which is chec!ed *for instance a radioK utton or chec! o%/ ':selected a user interface element ? which is selected *one or more option elements inside a select/ K not in the #SS spec, ut nonetheless supported y jQuery ' warning an ? element whose class is 'warning' '-+yid an ? element with ;0 equal to 'myid'. *)ill only match, at most, one element./ ':not)s* an ? element that does not match simple selector s ' . an A element descendant of an ? element ' / . an A element child of an ? element ' 0 . an A element immediately preceded y an ? element ' 1 . an A element preceded y an ? element '2.2G select all ? elements, A elements, and G elements

Supported, but different


$ll attri ute selectors are written li!e their @3ath counterKparts *in that all attri utes should egin with an 3 sym ol/.

'43foo5 an ? element with a 'foo' attri ute '43foo6,ar5 an ? element whose 'foo' attri ute "alue is e%actly equal to ' ar' '43foo76,ar5 an ? element whose 'foo' attri ute "alue egins e%actly with the string ' ar' '43foo86,ar5 an ? element whose 'foo' attri ute "alue ends e%actly with the string ' ar' '43foo&6,ar5 an ? element whose 'foo' attri ute "alue contains the su string ' ar' '43foo6,ar543,a96,op5 an ? element whose 'foo' attri ute "alue is e%actly equal to ' ar' and whose ' aG' attri ute is e%actly equal to ' op'

45678989:.doc / M

Not supported
jQuery only supports selectors that actually select 012 elements K e"erything else is ignored. ':link ':%isited an ? element eing the source anchor of a hyperlin! of which the target is not yet "isited *:lin!/ or already "isited *:"isited/ ':acti%e ':ho%er ':focus an ? element during certain user actions ':target an ? element eing the target of the referring +,; '::first(line the first formatted line of an ? element '::first(letter the first formatted letter of an ? element '::selection the portion of an ? element that is currently selected/highlighted y the user '::,efore generated content efore an ? element '::after generated content after an ? element jQuery doesn<t support the following selectors due to their lac! of realKworld usefulness: ':nth(last(child)n* an ? element, the nKth child of its parent, counting from the last one ':nth(of(type)n* an ? element, the nKth si ling of its type ':nth(last(of(type)n* an ? element, the nKth si ling of its type, counting from the last one ':first(of(type an ? element, first si ling of its type ':last(of(type an ? element, last si ling of its type ':only(of(type an ? element, only si ling of its type ':lang)fr* an element of type ? in language 'fr' '4foo16:test:5 an ? element whose 'foo' attri ute "alue is a list of spaceKseparated "alues, one of which is e%actly equal to 'test' '4hreflang;6:en:5 an ? element whose 'hreflang' attri ute has a hyphenKseparated list of "alues eginning *from the left/ with 'en'

Context and Anchoring


;n jQuery, unli!e real #SS, a selector e%pression may ha"e a conte%t other than the entire document, for instance with the function $(e$"r1 conte$t). Bou can anchor a #SSKli!e e%pression to the conte%t root y starting it with one of the selectors >, 2, or 3.

XPath Selectors
1ne of the selector languages that jQuery supports, as a part of its e%pression language is @3ath. jQuery supports asic @3ath e%pressions, in addition to #SS 5KC. (ere are some samples:

Location Paths
,elati"e to the entire (T2- document $(", tml,body,,"") $("body,,"") $("",..,div") ,elati"e to the conte%t node t is $("",-"1 t is) $(",",,a"1 t is)

45678989:.doc / 6

Supported Axis Selectors


"escendant ?lement has a descendant element $(",,div,,"") <hild ?lement has a child element $(",,div,"") Preceding Si,ling ?lement has an element efore it, $(",,div 3 form") Parent Selects the parent element of the element $(",,div,..,"")

on the same a%es

Supported Predicates
43foo5 (as an attri ute of foo $(",,in"ut#&c ecked%") 43foo6=test=5 $ttri ute foo is equal to test $(",,a#&ref0.nofollo+.%") 4>odelist5 ?lement contains a node list, for $(",,div#"%") $(",,div#",a%")

e%ample:

Supported Predicates, but differently


4last)*5 or 4position)*6last)*5 ecomes :last $(""(last") 4?5 or 4position)*6?5 ecomes :e@)?* or :first $(""(first") $(""(e)(*)") 4position)* A B5 ecomes :lt)B* $(""(lt(4)") 4position)* / !5 ecomes :gt)!* $(""(gt(5)")

Custom Selectors
jQuery includes some e%pressions that aren<t a"aila le in either #SS or @3ath, ut were found to e "ery handy, so were included. The following e%pressions< synta% is ased upon the "arious #SS selectors, of similar names.

Custom Selectors

:e%en Selects e"ery other *e"en/ element from the matched element set. :odd Selects e"ery other *odd/ element from the matched element set. :e@)?* and :nth)?* Selects the &th element from the matched element set :gt)>* Selects all matched elements whose inde% is greater than &. :lt)>* Selects all matched elements whose inde% is less than &. :first ?qui"alent to :e@)?* :last Selects the last matched element. :parent Selects all elements which ha"e child elements *including te%t/. :contains)=test=* Selects all elements which contain the specified te%t. :%isi,le Selects all "isi le elements *this includes items that ha"e a display of loc! or inline, a "isi ility of "isi le, and aren<t form elements of type hidden/

45678989:.doc / 5:

:hidden Selects all hidden elements *this includes items that ha"e a display of none, or a "isi ility of hidden, or are form elements of type hidden/

Some e%amples:

$(""(first").css("font6eig t"1"bold")' $("div( idden").s o+()' $(",div(contains(.test.)"1 t is). ide()'

orm Selectors
There are a few selectors for form elements:

:input Selects all form elements *input, select, te%tarea, utton/. :teCt Selects all te%t fields *typeE'te%t'/. :password Selects all password fields *typeE'password'/. :radio Selects all radio fields *typeE'radio'/. :check,oC Selects all chec! o% fields *typeE'chec! o%'/. :su,+it Selects all su mit uttons *typeE'su mit'/. :i+age Selects all form images *typeE'image'/. :reset Selects all reset uttons *typeE'reset'/. :,utton Selects all other uttons *typeE' utton'/. :file Selects all Ninput typeE'file'O.

$lso a"aila le is :hidden, see the description a o"e for details. ;t is recommended to pro"ide a conte%t when using the a o"e:
$(.#my7orm (in"ut.)

1r, if you ha"e already a reference to your form:


$(.in"ut(radio.1 my7orm)

This would select all input elements of type radio inside myAorm. +sing :radio is mostly the same as LPtypeEradioQ, ut should e slightly faster. Good to !now when wor!ing with large forms.

!ore Selectors
The jQuery selector system can e e%tended y third parties: 2ore Selectors 3lugin 2i!e $lsup on #ustom Selectors 3atch to allow selection y #SS property *full plugin to e released simultaneously with 5.5/

See Also

;nteracti"e jQuery selector tester

45678989:.doc / 55

Rate me: Using Aja


;n this part we write a small $ja% application, that allows the user to rate something, just li!e it is done on youtu e.com. )e need some ser"er code for this. 2y e%ample uses a php file that reads the 'rating' parameter and returns the num er of ratings and the a"erage rating. (a"e a loo! at rate.php for the ser"erKside code.
<<php de'i#e%.= *>?.3 .rati#2s.dat.&, 'u#ctio# put@co#te#ts%$'ile3$co#te#t& ( $' = 'ope#%$'ile3"w"&, 'write%$'3$co#te#t&, 'close%$'&, + i'%isset%$@>?AB?= 7"rati#2"9&& ( $rati#2 = $@>?AB?= 7"rati#2"9, $stored>ati#2s = u#serialiCe%'ile@2et@co#te#ts%= *>?&&, $stored>ati#2s79 = $rati#2, put@co#te#ts%= *>?3 serialiCe%$stored>ati#2s&&, $avera2e = rou#d%array@sum%$stored>ati#2s& / cou#t%$stored>ati#2s&3 D&, $cou#t = cou#t%$stored>ati#2s&, $xml = "<rati#2s><avera2e>$avera2e</avera2e><cou#t>$cou#t</cou#t></rati#2s>", header%.0o#te#t-type1 text/xml.&, echo $xml, + <>

)e don<t want this e%ample to wor! without $ja%, although it may e possi le, we therefore generate the necessary mar!up with jQuery and append it to a container di" with an ;0 of 'rating'.
$%docume#t&.ready%'u#ctio#%& ( // 2e#erate mar-up $%"/rati#2"&.appe#d%"Elease rate1 "&,

'or % var i = :, i <= F, i66 & $%"/rati#2"&.appe#d%"<a hre'=./.>" 6 i 6 "</a> "&, // add mar-up to co#tai#er a#d apply clic- ha#dlers to a#chors $%"/rati#2 a"&.clic-%'u#ctio#%e&( // stop #ormal li#- clice.preve#t)e'ault%&, // se#d request $.post%"rate.php"3 (rati#21 $%this&.html%&+3 'u#ctio#%xml& ( // 'ormat a#d output result $%"/rati#2"&.html% " ha#-s 'or rati#23 curre#t avera2e1 " 6 $%"avera2e"3 xml&.text%& 6 "3 #umber o' votes1 " 6 $%"cou#t"3 xml&.text%& &, +&, +&, +&,

45678989:.doc / 54

This snippet generates fi"e anchor elements and appends them to the container element with the id 'rating'. $fterwards, for e"ery anchor inside the container, a clic! handler is added. )hen the anchor is clic!ed, a post request is send to rate.php with the content of the anchor as a parameter. The result returned as a @2- is then added to the container, replacing the anchors. ;f you don<t ha"e a we ser"er with 3(3 installed at hand, you can loo! at an online e%ample. Aor a "ery nice e%ample of a rating system that e"en wor!s without =a"aScript, "isit softonic.de and clic! on 'RurG ewerten.' 2ore documentation of the $ja% methods of jQuery can e found in the $ja% 0ocumentation or on Jisual jQuery filed under $ja%. $ "ery common pro lem encountered when loading content y $ja% is this: )hen adding e"ent handlers to your document that should also apply to the loaded content, you ha"e to apply these handlers after the content is loaded. To pre"ent code duplication, you can delegate to a function. ?%ample:
'u#ctio# add0lic-Ha#dlers%& ( $%"a.remote"3 this&.clic-%'u#ctio#%& ( $%"/tar2et"&.load%this.hre'3 add0lic-Ha#dlers&, +&, + $%docume#t&.ready%add0lic-Ha#dlers&,

&ow add#lic!(andlers is called once when the 012 is ready and then e"erytime when a user clic!ed a lin! with the class remote and the content has finished loading. &ote the $("a.remote"1 t is) query, t is is passed as a conte%t: Aor the document ready e"ent, t is refers to the document, and it therefore searches the entire document for anchors with class remote. )hen add!lick8andlers is used as a call ac! for load(), t is refers to a different element: ;n the e%ample, the element with id target. This pre"ents that the clic! e"ent is applied again and again to the same lin!s, causing a crash e"entually. $nother common pro lem with call ac!s are parameters. Bou ha"e specified your call ac! ut need to pass an e%tra parameter. The easiest way to achie"e this is to wrap the call ac! inside another function:
// 2et some data var 'oobar = ..., // speci'y ha#dler3 it #eeds data as a paramter 'u#ctio# ha#dler%data& ( //... + // add clic- ha#dler a#d pass 'oobar! $%.a.&.clic-%'u#ctio#%&( ha#dler%'oobar&, +&, // i' you #eed the co#text o' the ori2i#al ha#dler3 use apply1 $%.a.&.clic-%'u#ctio#%&( ha#dler.apply%this3 7'oobar9&, +&,

)ith $ja% this simple we can co"er quite a lot of ')e 4.:'. &ow that we<"e loo!ed at some asic $ja%, let<s add some simple effects and animations to the page. Interesting links for this chapter: jQuery $ja% 0ocumentation jQuery $3; K #ontains description and e%amples for append and all other jQuery methods Thic!>o% K $ jQuery plugin that uses jQuery to enhance the famous light o%

45678989:.doc / 5C

ADAE2 DS#>2 DQuery with Struts !


http://www.arya566.com/strutsK4/aja%KjsonKwithKstrutsK4 ;t is assumed that readers of this article is familiar with Struts 4 Aramewor!, $ja% and =S1&. 1h, and of course, jQuery. $lso a disclaimer, some =a"a code snippets depicted in this article is ta!en from 2anning: Struts 4 in $ction written y 0onald >rown, #had 2ichael 0a"is, and Scott Stanlic!. $nother ca"eat, should there e any error or something else that eg to e criticiGed and laughed at in this post, please donSt hesitate to do so and of course, enact a proper enlightenment to the author *me/. (ereSs the idea, thereSs an application, o "iously a we application that presents its users with a form. $ user su mit the filled form, the applicationSs data ase contents are changed, and then the application updated its displayed "alues which related to the changed content without e"er lea"ing the page. $ja% definitely comes to mind, and as ; uilt the application using the Struts 4 framewor!, my quest to deli"er this feature egins with a Google search for T$ja% with Struts 4.U #ut to the chase, hereSs my penciled writing on the issue.

5. ThereSs a jsp file, coupled with a =a"aScript file, that contains the form handler and mechanism to su mit the form to a ser"erKside resource. $s ;Sm using $ja% su mit mechanism, rather than using (T2- form and su mit tag, ;Sm using a =a"aScript onclic! function that sends a request and recei"e a response in $ja% manners. To further simplify requestKresponse communication from the client to the ser"er, ; facilitate this transfer with =S1& notations *in itself is a redundant elongation of the word since =S1& already stands

45678989:.doc / 5F

for =a"aScript 1 ject >otation/ and with jQuery aid, ; had this function in my =a"aScript file to forward the request from client to a certain ser"erKside resource using a jQuery function $.get9:;<.
var divisio#Game = $%./divisio#Game.&.val%&, $.2etH=*G%.add)ivisio#.actio#.3 (.divisio#.#ame.1 divisio#Game+3 'u#ctio#%data& ( $%..status.& .css%%(bac-2rou#d1 ./I'I.3 border1 ./I8I solid :px.+&& .'adeJ#%"slow"& .a#imate%(opacity1 :+3 :F88& .'ade*ut%"slow"&, var divisio#"ist = %data.list&,
$%./divisio#=elect.&.load=elect%divisio#"ist7"arya:II.e#tity.)ivisio#"9&,

+ &,

The first line of the code, using a standard and wellK!nown VIS notation for jQuery, select an element from a 012 *0ocument 1 ject 2odel/ that made up the clientSs (T2- which identified y an id attri ute named division<ame. ;n my case, the only element in the clientSs code which has an id of division<ame is a (T2- standard te%tfield, therefore the first line of this code selects the "alue from this te%tfield, and store it in a "aria le called division<ame. The second line, up until the "ery last of the line, is a single function from jQuery *get9:;</ and it has three parameters passed in. This function initiates a G?T request to the ser"er to the specified +,passedKin as its first parameter *add=ivision.action/, with parameters sent to the said +,- passedKin as its second parameter *>.division.name.( division<ame?. (ere, it says that the +,- is going to ha"e its division.name parameter sets to a "alue ta!en from "aria le identified y division<ame/. The third parameter is a call ac! function, in"o!ed when the request completes. The =S1& string "alue resulted from the response is passed to this function as its first parameter. 1ptionally, this function also has a second parameter, which is status and not shown here. The call ac! function, as shown in the code a o"e then sets the 012 element in the client code identified y a class named status with some simple animation. $gain, using a standard *and hopefully tri"ial/ jQuery. The function then reads the =S1& string passed in as response, and then populate a certain select component in the resulted (T2- page with the updated "alue using a custom and handK made jQuery function load:elect. &ow, ac! to the ser"er resource called from this function, add=ivision.action. ; ha"e a struts.$ml configured to map this action. (ereSs the configuration:
<result-types> <result-type #ame="customH=*G" class="arya:II.actio#.H=*G>esult"/> </result-types>

45678989:.doc / 57

<actio# #ame="add)ivisio#" method="add)ivisio#" class="arya:II.actio#.?mployee5ctio#"> <result-typeresult-type="customH=*G">divisio#</result-type> </actio#-#ame>

;t is easy to see that line num er F of the code a o"e mapped add=ivision.action request to a Em"loyee@ction class and to the add=ivision method of that class. &ow hereSs some of the Em"loyee@ction classS contents, y the way:
private )ivisio# divisio#, private "ist<)ivisio#> all)ivisio#, private *bject jso#!odel, public =tri#2 add)ivisio#%& ( ?#tity ra#sactio# et = 2et?#tity!a#a2er%&.2et ra#sactio#%&, try ( et.be2i#%&, 2et?#tity!a#a2er%&.persist%divisio#&, et.commit%&, + catch %?xceptio# ex& ( ex.pri#t=tac- race%&, + setH=*G!odel%2e#eric?#tity.2et5ll)ivisio#s%&&, retur# =B00?==, + // Ketter a#d setter methods are #ot show# 'or simplicity

&ow if you loo! into the first code e%cerpt *the =a"aScript one/ line num er two, youSll see that the client called add=ivision.action which mapped with the method add=ivision from Em"loyee@ction class through a struts.$ml configuration *second code e%cerpt, the @2- one/. Arom the first e%cerpt youSll also see that the request also passed a parameter division.name with a "alue identified y division<ame. )ith Struts 4 Aramewor!, this parameter would translate into a call to set=ivision(args).set<ame(args) from the called action class with a proper "alue passed in as its argument. Ainally, from the action class descri ed in third code e%cerpt a o"e *the =a"a one/, you could see that the pre"ious call descri ed in the pre"ious paragraph would set the pri"ate property =ivision *line 5 and further, the pri"ate property name in this class would ha"e an equi"alent =a"a>eans getter and setter method which are not shown/ from this class to hold the "alue division<ame passed in from the client.

45678989:.doc / 59

$ call to add=ivision method *line 8 and eyond/ then tells the =3$ *=a"a 3ersistence $3;/ to persist this newly created di"ision o ject to the data ase. 1ne ca"eat, on line 58 of the action class e%ample a o"e, we sets a property called AsonBodel with a "alue o tained from genericEntity.get@ll=ivisions() method e%ecution. This method *not shown/ retrie"es all the 0i"ision o jects from the data ase and populated them into an instance of Cist. $lso note, that this property *AsonBodel/ is set to hold an instance of ;bAect class. 4. This step pushes an o ject from the e%ecuted action class to a Dalue:tack and then informs the framewor! a out this o ject and its type *9:;</esult/, and treats it as a result. >ac! to the configuration @2- shown in the second code e%cerpt line 7, youSll see that the result of the add=ivision.action is mapped with a type custom9:;<. &ow, this type is defined properly in line 4, mapped to a class called aryaEFF.action.9:;</esult, and hereSs the e%cerpt of that class.
public class H=*G>esult impleme#ts >esult ( public static 'i#al =tri#2 )?L5B" @E5>5! = "class5lias", =tri#2 class5lias, public =tri#2 2et0lass5lias%& ( retur# class5lias, + public void set0lass5lias%=tri#2 alias& ( this.class5lias = alias, + Eublic void execute%5ctio#J#vocatio# i#vocatio#& throws ?xceptio# ( =ervlet5ctio#0o#text.2et>espo#se%&.set0o#te#t ype%"text/plai#"&,
Eri#tMriter respo#se=tream = =ervlet5ctio#0o#text.2et>espo#se%&.2etMriter%&,

Nalue=tac- value=tac- = i#vocatio#.2et=tac-%&, *bject jso#!odel = value=tac-.'i#dNalue%"jso#!odel"&, O=tream xstream = #ew O=tream%#ew Hettiso#!appedOml)river%&&, i' %class5lias == #ull& ( class5lias = "object", + xstream.alias%class5lias3 jso#!odel.2et0lass%&&, respo#se=tream.pri#tl#%xstream.toO!"%jso#!odel&&, + +

45678989:.doc / 58

C. ;n order to get a proper treatment as a result y the Struts 4 framewor!, a class needs to implement /esult class which is e%actly what this class did as shown in line num er one. $ny class that implemented /esult class therefore needs to implement e$ecute method *line 57/. To shorten the discussion, the method implemented here said that itSs going to return a response within a Tte%t/plainU content type, then loo!s into Dalue:tack for a "alue idKed with a string "AsonBodel" which as shown in the third code e%cerpt *the =a"a action class code/ a o"e sets to hold "alue returned from a query of all =ivision entity stored in the data ase. Ainally, the resulted "alue is con"erted to a something else *alas, ; need to see more of it/ representa le as =S1& string. ; achie"ed this with helps from @Stream li rary and =ettison li rary. F. The final step is to sent ac! the =S1& String to the client. This is most tri"ial. The only pro lem was to determine how the resulted string is returned ac! from the ser"er. ;n my case, the result String loo!s li!e this. WUlistU:WUarya566.entity.0i"isionU:LW'id':5,'name':'Sales 0epartment'X,W'id':4,'name':'$ccounting 0epartment'XQXX ;f this notation loo!s alien to you, etter head to =S1& for a proper e%planation. (owe"er, as ; want to populate my select element with these data, hereSs how ; retrie"ed the meaningful data from the returned String *also shown in the first code e%cerpt of this article/.
var divisio#"ist = %data.list&, $%./divisio#=elect.&.load=elect%divisio#"ist7"arya:II.e#tity.)ivisio#"9&,

The first line VlistS is o "iously refer to the same word VlistS as shown in the result, and it is. $s we could see from the first code e%cerpt *the =a"aScript one/, the whole =S1& String is returned and stored in a "aria le called data, and =S1& treats this "aria le as any other o ject, therefore, calling data.list would yield WUarya566.entity.0i"isionU:LW'...'XQX. The second line then o tain the array "alue of data.listL'arya566.entity.0i"ision'Q and passed it to a function that populates the select element with "alues o tained from this array. i.e. data.list7"arya:II.e#tity.)ivisio#"9789.#ame would yield the first name element which according to this case, a string "alued TSales 0epartment.U

45678989:.doc / 5M

http://stac!o"erflow.com/questions/75:MFC/aja%K"alidationsKinKstrutsK4 ;f you want to use $=$@ to do some ser"erKside "alidation *and you<r using =Query/ this should at least get you started:
'u#ctio# validate%'ieldGame& ( $.2et%./validatio#.php.3 (.value. 1 'ieldGame.value3 .#ame. 1 'ieldGame.#ame+3 'u#ctio#%data3 text=tatus& ( i'%data& ( 'ieldGame.style.class = .validLormJ#put., + else ( 'ieldGame.style.class = .i#validLormJ#put., + +& +

45678989:.doc / 56

Potrebbero piacerti anche