PDA

View Full Version : [JQuery ?!?] Da dove iniziare per capire questo esempio?


e-commerce84
14-11-2012, 12:46
Salve a tutti,
ammetto la mia ignoranza per quanto riguarda il mondo JavaScript ed in particolar modo JQuery. Fino ad oggi le mie esperienze con AJAX sono state limitate all'uso di determinati framework di presentazione in JAVA che wrappano al loro interno AJAX rendendo Javascript completamente trasparente allo sviluppatore (in pratica forniscono una serie di tag library con cose prefatte)...framework tipo IceFaces, PrimeFaces, JSF per capirsi...

Al momento mi stò trovando a studiare un esempio dello showcase di Spring MVC (un framework Java per creare web application) e tale esempio sembra fare largo uso di JQuery per creare un'interfaccia RIA (quindi sfrutta AJAX)...proprio per questo ho bisogno del vostro aiuto per capire, almeno a grandi linee, come funziona e cosa andarmi a vedere\studiare...dico a grandi linee perchè per il momento sono più interessato a studiare il framework Spring più che JQuery...ora non voglio approfondire più di tanto tale tecnologia ma solo avere dei concetti base per interpretare gli output...

Sostanzialmente questa è l'immagine di come si presenta la mia web application:

http://gordondickens.com/wordpress/wp-content/uploads/2010/08/mvc-showcase-main-page-capture.png

Come potete vedere ci sono una serie di tab: "Simple", "Mapping Request", "Obtaining Result Data", etcetc.

Di default siamo quando accediamo alla web application siamo su "Simple".

Dentro al tab "Simple" ho 2 links: "Get /simple" e "Get /simple/revisited"

Clickando su uno di questi link accade che accanto ad esso compare un messaggio di "Hello World", se volete una visione di cosa accade potete vederlo al minuto 1:42 di questo video: http://s3.springsource.org/MVC/mvc-showcase-screencast.mov

Allora...veniamo a noi...credo che entrambe le cose di cui ho parlato (la creazione del menù a tab ed il far comparire il messaggino di "Hello World" accanto al link una volta che quest'ultimo è stato clickato siano cose implementate tramite JQuery)

In praticolar modo il far comparire una scritta accanto al link dopo averlo clickato, senza ricaricare tutta la pagina, dovrebbe proprio essere un esempio dell'uso di una metodologia AJAX...a grandissime linee credo che per fare questa cosa JQuery vada a modificare il DOM una volta che clicko il link (cioè...più a basso livello il mio esempio funziona così: quando l'utente clicka sul link si genera una HTTP Request verso la risorsa /simple, tale richiesta è mappata dal framework Spring verso un metodo di una classe controllore che semplicemente ritorna la stringa "Hello World" messa all'interno del body della HTTP Response del server, così una volta che tale HTTP Response arriva al cliente...beh suppongo che JQuery la estragga ed inserisca tale stringa accanto al link modificando il DOM...credo...sono supposizioni mie...correggetemi se dico cavolate)


Solo che...non ho idea di come lo faccia e di cosa andarmi a vedere per capirlo...questo è il codice della mia pagina home.jsp che fà uso di JQuery:


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>spring-mvc-showcase</title>
<link href="<c:url value="/resources/form.css" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="/resources/jqueryui/1.8/themes/base/jquery.ui.all.css" />" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1><a href="<c:url value="/" />">spring-mvc-showcase</a></h1>
<p>Recommended: Using a Web Developer tool such a Firebug to inspect the client/server interaction</p>
<div id="tabs">
<ul>
<li><a href="#simple">Simple</a></li>
<li><a href="#mapping">Request Mapping</a></li>
<li><a href="#data">Request Data</a></li>
<li><a href="#responses">Response Writing</a></li>
<li><a href="#messageconverters">Message Converters</a></li>
<li><a href="#views">View Rendering</a></li>
<li><a href="#convert">Type Conversion</a></li>
<li><a href="#validation">Validation</a></li>
<li><a href="<c:url value="/form" />" title="forms">Forms</a></li>
<li><a href="<c:url value="/fileupload" />" title="fileupload">File Upload</a></li>
<li><a href="#exceptions">Exception Handling</a></li>
<li><a href="#redirect">Redirecting</a></li>
<li><a href="#async">Async Requests</a></li>
</ul>
<div id="simple">
<h2>Simple</h2>
<p>
See the <code>org.springframework.samples.mvc.simple</code> package for the @Controller code
</p>
<ul>
<li>
<a id="simpleLink" class="textLink" href="<c:url value="/simple" />">GET /simple</a>
</li>

<li>
<a id="simpleLink2" class="textLink" href="<c:url value="hello.html" />">GET hello.html</a>
</li>

<li>
<a href="hello.html">Say Hello</a>
</li>

<li>
<a id="simpleRevisited" class="textLink" href="<c:url value="/simple/revisited" />">GET /simple/revisited</a>
</li>
</ul>
</div>
<div id="mapping">
<h2>Request Mapping</h2>
<p>
See the <code>org.springframework.samples.mvc.mapping</code> package for the @Controller code
</p>
<ul>
<li>
<a id="byPath" class="textLink" href="<c:url value="/mapping/path" />">By path</a>
</li>
<li>
<a id="byPathPattern" class="textLink" href="<c:url value="/mapping/path/wildcard" />">By path pattern</a>
</li>
<li>
<a id="byMethod" class="textLink" href="<c:url value="/mapping/method" />">By path and method</a>
</li>
<li>
<a id="byParameter" class="textLink" href="<c:url value="/mapping/parameter?foo=bar" />">By path, method, and presence of parameter</a>
</li>
<li>
<a id="byNotParameter" class="textLink" href="<c:url value="/mapping/parameter" />">By path, method, and not presence of parameter</a>
</li>
<li>
<a id="byHeader" href="<c:url value="/mapping/header" />">By presence of header</a>
</li>
<li>
<a id="byHeaderNegation" class="textLink" href="<c:url value="/mapping/header" />">By absence of header</a>
</li>
<li>
<form id="byConsumes" class="readJsonForm" action="<c:url value="/mapping/consumes" />" method="post">
<input id="byConsumesSubmit" type="submit" value="By consumes" />
</form>
</li>
<li>
<a id="byProducesAcceptJson" class="writeJsonLink" href="<c:url value="/mapping/produces" />">By produces via Accept=application/json</a>
</li>
<li>
<a id="byProducesAcceptXml" class="writeXmlLink" href="<c:url value="/mapping/produces" />">By produces via Accept=appilcation/xml</a>
</li>
<li>
<a id="byProducesJsonExt" class="writeJsonLink" href="<c:url value="/mapping/produces.json" />">By produces via ".json"</a>
</li>
<li>
<a id="byProducesXmlExt" class="writeXmlLink" href="<c:url value="/mapping/produces.xml" />">By produces via ".xml"</a>
</li>
</ul>
</div>
<div id="data">
<h2>Request Data</h2>
<p>
See the <code>org.springframework.samples.mvc.data</code> package for the @Controller code
</p>
<ul>
<li>
<a id="param" class="textLink" href="<c:url value="/data/param?foo=bar" />">Query parameter</a>
</li>
<li>
<a id="group" class="textLink" href="<c:url value="/data/group?param1=foo&param2=bar&param3=baz" />">Group of query parameters</a>
</li>
<li>
<a id="var" class="textLink" href="<c:url value="/data/path/foo" />">Path variable</a>
</li>
<li>
<a id="matrixVar" class="textLink" href="<c:url value="/data/matrixvars;foo=bar/simple" />">Matrix variable</a>
</li>
<li>
<a id="matrixVarMultiple" class="textLink" href="<c:url value="/data/matrixvars;foo=bar1/multiple;foo=bar2" />">Matrix variables (multiple)</a>
</li>
<li>
<a id="header" class="textLink" href="<c:url value="/data/header" />">Header</a>
</li>
<li>
<form id="requestBody" class="textForm" action="<c:url value="/data/body" />" method="post">
<input id="requestBodySubmit" type="submit" value="Request Body" />
</form>
</li>
<li>
<form id="requestBodyAndHeaders" class="textForm" action="<c:url value="/data/entity" />" method="post">
<input id="requestBodyAndHeadersSubmit" type="submit" value="Request Body and Headers" />
</form>
</li>
</ul>
<div id="standardArgs">
<h3>Standard Resolvable Web Arguments</h3>
<ul>
<li>
<a id="request" class="textLink" href="<c:url value="/data/standard/request" />">Request arguments</a>
</li>
<li>
<form id="requestReader" class="textForm" action="<c:url value="/data/standard/request/reader" />" method="post">
<input id="requestReaderSubmit" type="submit" value="Request Reader" />
</form>
</li>
<li>
<form id="requestIs" class="textForm" action="<c:url value="/data/standard/request/is" />" method="post">
<input id="requestIsSubmit" type="submit" value="Request InputStream" />
</form>
</li>
<li>
<a id="response" class="textLink" href="<c:url value="/data/standard/response" />">Response arguments</a>
</li>
<li>
<a id="writer" class="textLink" href="<c:url value="/data/standard/response/writer" />">Response Writer</a>
</li>
<li>
<a id="os" class="textLink" href="<c:url value="/data/standard/response/os" />">Response OutputStream</a>
</li>
<li>
<a id="session" class="textLink" href="<c:url value="/data/standard/session" />">Session</a>
</li>
</ul>
</div>
<div id="customArgs">
<h3>Custom Resolvable Web Arguments</h3>
<ul>
<li>
<a id="customArg" class="textLink" href="<c:url value="/data/custom" />">Custom</a>
</li>
</ul>
</div>
</div>
<div id="responses">
<h2>Response Writing</h2>
<p>
See the <code>org.springframework.samples.mvc.response</code> package for the @Controller code
</p>
<ul>
<li>
<a id="responseBody" class="textLink" href="<c:url value="/response/annotation" />">@ResponseBody</a>
</li>
<li>
<a id="responseCharsetAccept" class="utf8TextLink" href="<c:url value="/response/charset/accept" />">@ResponseBody (UTF-8 charset requested)</a>
</li>
<li>
<a id="responseCharsetProduce" class="textLink" href="<c:url value="/response/charset/produce" />">@ResponseBody (UTF-8 charset produced)</a>
</li>
<li>
<a id="responseEntityStatus" class="textLink" href="<c:url value="/response/entity/status" />">ResponseEntity (custom status)</a>
</li>
<li>
<a id="responseEntityHeaders" class="textLink" href="<c:url value="/response/entity/headers" />">ResponseEntity (custom headers)</a>
</li>
</ul>
</div>
<div id="messageconverters">
<h2>Http Message Converters</h2>
<p>
See the <code>org.springframework.samples.mvc.messageconverters</code> package for the @Controller code
</p>
<div id="stringMessageConverter">
<h3>StringHttpMessageConverter</h3>
<ul>
<li>
<form id="readString" class="textForm" action="<c:url value="/messageconverters/string" />" method="post">
<input id="readStringSubmit" type="submit" value="Read a String" />
</form>
</li>
<li>
<a id="writeString" class="textLink" href="<c:url value="/messageconverters/string" />">Write a String</a>
</li>
</ul>
<h3>FormHttpMessageConverter</h3>
<ul>
<li>
<form id="readForm" action="<c:url value="/messageconverters/form" />" method="post">
<input id="readFormSubmit" type="submit" value="Read Form Data" />
</form>
</li>
<li>
<a id="writeForm" href="<c:url value="/messageconverters/form" />">Write Form Data</a>
</li>
</ul>
<h3>Jaxb2RootElementHttpMessageConverter</h3>
<ul>
<li>
<form id="readXml" class="readXmlForm" action="<c:url value="/messageconverters/xml" />" method="post">
<input id="readXmlSubmit" type="submit" value="Read XML" />
</form>
</li>
<li>
<a id="writeXmlAccept" class="writeXmlLink" href="<c:url value="/messageconverters/xml" />">Write XML via Accept=application/xml</a>
</li>
<li>
<a id="writeXmlExt" class="writeXmlLink" href="<c:url value="/messageconverters/xml.xml" />">Write XML via ".xml"</a>
</li>
</ul>
<h3>MappingJacksonHttpMessageConverter</h3>
<ul>
<li>
<form id="readJson" class="readJsonForm" action="<c:url value="/messageconverters/json" />" method="post">
<input id="readJsonSubmit" type="submit" value="Read JSON" />
</form>
</li>
<li>
<form id="readJsonInvalid" class="readJsonForm invalid" action="<c:url value="/messageconverters/json" />" method="post">
<input id="readInvalidJsonSubmit" type="submit" value="Read invalid JSON (400 response code)" />
</form>
</li>
<li>
<a id="writeJsonAccept" class="writeJsonLink" href="<c:url value="/messageconverters/json" />">Write JSON via Accept=application/json</a>
</li>
<li>
<a id="writeJsonExt" class="writeJsonLink" href="<c:url value="/messageconverters/json.json" />">Write JSON via ".json"</a>
</li>
</ul>
<h3>AtomFeedHttpMessageConverter</h3>
<ul>
<li>
<form id="readAtom" action="<c:url value="/messageconverters/atom" />" method="post">
<input id="readAtomSubmit" type="submit" value="Read Atom" />
</form>
</li>
<li>
<a id="writeAtom" href="<c:url value="/messageconverters/atom" />">Write Atom</a>
</li>
</ul>
<h3>RssChannelHttpMessageConverter</h3>
<ul>
<li>
<form id="readRss" action="<c:url value="/messageconverters/rss" />" method="post">
<input id="readRssSubmit" type="submit" value="Read Rss" />
</form>
</li>
<li>
<a id="writeRss" href="<c:url value="/messageconverters/rss" />">Write Rss</a>
</li>
</ul>
</div>
</div>
<div id="views">
<h2>View Rendering</h2>
<p>
See the <code>org.springframework.samples.mvc.views</code> package for the @Controller code
</p>
<ul>
<li>
<a href="<c:url value="/views/html" />">HTML generated by JSP template</a>
</li>
</ul>
<ul>
<li>
<a href="<c:url value="/views/viewName" />">DefaultRequestToViewNameTranslator convention</a>
</li>
</ul>
<ul>
<li>
<a href="<c:url value="/views/pathVariables/bar/apple" />">Using path variables in a view template</a>
</li>
</ul>
<ul>
<li>
<a href="<c:url value="/views/dataBinding/bar/apple" />">Data binding with URI variables</a>
</li>
</ul>
</div>
<div id="convert">
<h2>Type Conversion</h2>
<p>
See the <code>org.springframework.samples.mvc.convert</code> package for the @Controller code
</p>
<ul>
<li>
<a id="primitive" class="textLink" href="<c:url value="/convert/primitive?value=3" />">Primitive</a>
</li>
<li>
<a id="date" class="textLink" href="<c:url value="/convert/date/2010-07-04" />">Date</a>
</li>
<li>
<a id="collection" class="textLink" href="<c:url value="/convert/collection?values=1&values=2&values=3&values=4&values=5" />">Collection 1 (multi-value parameter)</a>
</li>
<li>
<a id="collection2" class="textLink" href="<c:url value="/convert/collection?values=1,2,3,4,5" />">Collection 2 (single comma-delimited parameter value)</a>
</li>
<li>
<a id="formattedCollection" class="textLink" href="<c:url value="/convert/formattedCollection?values=2010-07-04,2011-07-04" />">@Formatted Collection</a>
</li>
<li>
<a id="valueObject" class="textLink" href="<c:url value="/convert/value?value=123456789" />">Custom Value Object</a>
</li>
<li>
<a id="customConverter" class="textLink" href="<c:url value="/convert/custom?value=123-45-6789" />">Custom Converter</a>
</li>
</ul>
<div id="convert-bean">
<h3>JavaBean Property Binding</h3>
<ul>
<li>
<a id="primitiveProp" class="textLink" href="<c:url value="/convert/bean?primitive=3" />">Primitive</a>
</li>
<li>
<a id="dateProp" class="textLink" href="<c:url value="/convert/bean?date=2010-07-04" />">Date</a>
</li>
<li>
<a id="maskedProp" class="textLink" href="<c:url value="/convert/bean?masked=(205) 333-3333" />">Masked</a>
</li>
<li>
<a id="listProp" class="textLink" href="<c:url value="/convert/bean?list[0]=1&list[1]=2&list[2]=3" />">List Elements</a>
</li>
<li>
<a id="formattedListProp" class="textLink" href="<c:url value="/convert/bean?formattedList[0]=2010-07-04&formattedList[1]=2011-07-04" />">@Formatted List Elements</a>
</li>
<li>
<a id="mapProp" class="textLink" href="<c:url value="/convert/bean?map[0]=apple&map[1]=pear" />">Map Elements</a>
</li>
<li>
<a id="nestedProp" class="textLink" href="<c:url value="/convert/bean?nested.foo=bar&nested.list[0].foo=baz&nested.map[key].list[0].foo=bip" />">Nested</a>
</li>
</ul>
</div>
</div>
<div id="validation">
<h2>Validation</h2>
<p>
See the <code>org.springframework.samples.mvc.validation</code> package for the @Controller code
</p>
<ul>
<li>
<a id="validateNoErrors" class="textLink" href="<c:url value="/validate?number=3&date=2029-07-04" />">Validate, no errors</a>
</li>
<li>
<a id="validateErrors" class="textLink" href="<c:url value="/validate?number=3&date=2010-07-01" />">Validate, errors</a>
</li>
</ul>
</div>
<div id="exceptions">
<h2>Exception Handling</h2>
<p>
See the <code>org.springframework.samples.mvc.exceptions</code> package for the @Controller code
</p>
<ul>
<li>
<a id="exception" class="textLink" href="<c:url value="/exception" />">@ExceptionHandler in Controller</a>
</li>
<li>
<a id="globalException" class="textLink" href="<c:url value="/global-exception" />">Global @ExceptionHandler</a>
</li>
</ul>
</div>
<div id="redirect">
<h2>Redirecting</h2>
<p>
See the <code>org.springframework.samples.mvc.redirect</code> package for the @Controller code
</p>
<ul>
<li>
<a href="<c:url value="/redirect/uriTemplate" />">URI Template String</a>
</li>
<li>
<a href="<c:url value="/redirect/uriComponentsBuilder" />">UriComponentsBuilder</a>
</li>
</ul>
</div>
<div id="async">
<h2>Async Requests</h2>
<p>
<em>Note: Links may take 2-3 seconds to complete.</em>
</p>
<p>
See the <code>org.springframework.samples.mvc.async</code> package for the @Controller code.
</p>
<ul>
<li>
<a id="callableResponseBodyLink" class="textLink"
href="<c:url value="/async/callable/response-body" />">GET /async/callable/response-body</a>
</li>
<li>
<a id="callableViewLink" class="textLink"
href="<c:url value="/async/callable/view" />">GET /async/callable/view</a>
</li>
<li>
<a id="callableExceptionLink" class="textLink"
href="<c:url value="/async/callable/exception" />">GET /async/callable/exception</a>
</li>
<li>
<a id="callableUnhandledExceptionLink" class="textLink"
href="<c:url value="/async/callable/exception?handled=false" />">GET /async/callable/exception?handled=false</a>
(500 Error expected)
</li>
<li>
<a id="callableCustomTimeoutLink" class="textLink"
href="<c:url value="/async/callable/custom-timeout-handling" />">GET /async/callable/custom-timeout-handling</a>
</li>
<li>
<a id="deferredResultSuccessLink" class="textLink"
href="<c:url value="/async/deferred-result/response-body" />">GET /async/deferred-result/response-body</a>
</li>
<li>
<a id="deferredResultModelAndViewLink" class="textLink"
href="<c:url value="/async/deferred-result/model-and-view" />">GET /async/deferred-result/model-and-view</a>
</li>
<li>
<a id="deferredResultErrorLink" class="textLink"
href="<c:url value="/async/deferred-result/exception" />">GET /async/deferred-result/exception</a>
</li>
<li>
<a id="deferredResultTimeoutValueLink" class="textLink"
href="<c:url value="/async/deferred-result/timeout-value" />">GET /async/deferred-result/timeout-value</a>
</li>
</ul>
</div>
</div>
<script type="text/javascript" src="<c:url value="/resources/jquery/1.6/jquery.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryform/2.8/jquery.form.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.core.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.widget.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.tabs.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/json2.js" />"></script>
<script>
MvcUtil = {};
MvcUtil.showSuccessResponse = function (text, element) {
MvcUtil.showResponse("success", text, element);
};
MvcUtil.showErrorResponse = function showErrorResponse(text, element) {
MvcUtil.showResponse("error", text, element);
};
MvcUtil.showResponse = function(type, text, element) {
var responseElementId = element.attr("id") + "Response";
var responseElement = $("#" + responseElementId);
if (responseElement.length == 0) {
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
} else {
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
responseElement = $("#" + responseElementId);
}
responseElement.fadeIn("slow");
};
MvcUtil.xmlencode = function(xml) {
//for IE
var text;
if (window.ActiveXObject) {
text = xml.xml;
}
// for Mozilla, Firefox, Opera, etc.
else {
text = (new XMLSerializer()).serializeToString(xml);
}
return text.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
.replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
};
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();

// Append '#' to the window location so "Back" returns to the selected tab
// after a redirect or a full page refresh (e.g. Views tab).

// However, note this general disclaimer about going back to previous tabs:
// http://docs.jquery.com/UI/API/1.8/Tabs#Back_button_and_bookmarking

$("#tabs").bind("tabsselect", function(event, ui) { window.location.hash = ui.tab.hash; });


$("a.textLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("a.utf8TextLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", beforeSend: function(req) { req.setRequestHeader("Accept", "text/plain;charset=UTF-8"); }, success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("form.textForm").submit(function(event) {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "foo", contentType: "text/plain", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#readForm").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "foo=bar&fruit=apple", contentType: "application/x-www-form-urlencoded", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeForm").click(function() {
var link = $(this);
$.ajax({ url: this.href, dataType: "text", beforeSend: function(req) { req.setRequestHeader("Accept", "application/x-www-form-urlencoded"); }, success: function(form) { MvcUtil.showSuccessResponse(form, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("form.readXmlForm").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><javaBean><foo>bar</foo><fruit>apple</fruit></javaBean>", contentType: "application/xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("a.writeXmlLink").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
if (!this.url.match(/\.xml$/)) {
req.setRequestHeader("Accept", "application/xml");
}
},
success: function(xml) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(xml), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("form.readJsonForm").submit(function() {
var form = $(this);
var button = form.children(":first");
var data = form.hasClass("invalid") ?
"{ \"foo\": \"bar\" }" :
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }";
$.ajax({ type: "POST", url: form.attr("action"), data: data, contentType: "application/json", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("a.writeJsonLink").click(function() {
var link = $(this);
$.ajax({ url: this.href,
beforeSend: function(req) {
if (!this.url.match(/\.json$/)) {
req.setRequestHeader("Accept", "application/json");
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});

$("#readAtom").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: '<?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"><title>My Atom feed</title></feed>', contentType: "application/atom+xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeAtom").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
req.setRequestHeader("Accept", "application/atom+xml");
},
success: function(feed) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(feed), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("#readRss").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: '<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"><channel><title>My RSS feed</title></channel></rss>', contentType: "application/rss+xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeRss").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
req.setRequestHeader("Accept", "application/rss+xml");
},
success: function(feed) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(feed), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("#byHeader").click(function(){
var link = $(this);
$.ajax({ url: this.href, dataType: "text", beforeSend: function(req) { req.setRequestHeader("FooHeader", "foo"); }, success: function(form) { MvcUtil.showSuccessResponse(form, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

});
</script>
</body>
</html>


Come potete vedere ho un div esterno con id="tabs" che contiene una lista non ordinata contenente links a tutti i vari tab del mio menù. Questi link non puntano ad indirizzi reali ma hanno un valore simbolico del tipo: #simple

Poi al di sotto di tale lista non ordinata ho una serie di div che hanno ognuno id uguale ad uno dei "link simbolici" dei vari elementi nella lista non ordinata...e di fatto ognuno di questi link poi conterrà il codice associato ad ogni "pagina" per ogni tab...per essere più concreti:

Dentro l'UL ho un LI che contiene un link simbolico verso #simple, quindi poi avrò un div con id uguale a "simple" che conterrà il codice di ciò che viene visualizzato quando clicko sul link del menu relativo al tab simple.

Credo che questa sia la sintassi di come JQuery implementa questo tipo di menù a tab, giusto?

Ora per quanto riguarda il tab simple ed il suo contenuto ho che sono presenti dei link, ad esempio ho:


<li>
<a id="simpleLink" class="textLink" href="<c:url value="/simple" />">GET /simple</a>
</li>


Tale link ha id: "simpleLink", quando clicko su di esso accanto ad esso mi comprare il messaggio di "Hello World", credo che in qualche modo ci sia uno script che modifichi il DOM e che vada a dire: Metti il messaggio di hello world ricevuto nel mody della http response accanto al link avente id="simpleLink"

La domanda è...ma dove stà questo script ?!?! booo

Se vedete verso la fine del codice, dopo la chiusura del div principale avente id "tags" per intenderci" ho una serie di cose di JavaScript che fanno riferimento a JQuery...e penso che il segreto sia là...anche se mi risulta piuttosto oscuro...

Intanto ho qualcosa come:


<script type="text/javascript" src="<c:url value="/resources/jquery/1.6/jquery.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryform/2.8/jquery.form.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.core.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.widget.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/jqueryui/1.8/jquery.ui.tabs.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/json2.js" />"></script>


E non capisco se quà si stà semplicemente importando il framework JQuery per renderlo attivo all'interno della mia pagina o se in realtà stà importando molto altro...mi date una mano a capire cosa stò importando? Questa comunque dovrebbe essere roba prefatta credo, sono andato a vedere nei file .js all'interno della mia cartella /resources e si tratta di file molto grossi...anche varie migliaia di linee di codice...

Poi al di sotto ho una serie di script che credo siano stati scritti da chi ha sviluppato l'esempio che stò studiando, non capisco cosa facciano...diciamo che al momento mi basterebbe anche solo sapere quale di questi gestisca il comportamento AJAX che prevede: click sul link, ricevi HTTP Response, estrai messaggio di Hello Worrld dal body di tale response, modifica il DOM e visualizza messaggio accanto al link:


<script>
MvcUtil = {};
MvcUtil.showSuccessResponse = function (text, element) {
MvcUtil.showResponse("success", text, element);
};
MvcUtil.showErrorResponse = function showErrorResponse(text, element) {
MvcUtil.showResponse("error", text, element);
};
MvcUtil.showResponse = function(type, text, element) {
var responseElementId = element.attr("id") + "Response";
var responseElement = $("#" + responseElementId);
if (responseElement.length == 0) {
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
} else {
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
responseElement = $("#" + responseElementId);
}
responseElement.fadeIn("slow");
};
MvcUtil.xmlencode = function(xml) {
//for IE
var text;
if (window.ActiveXObject) {
text = xml.xml;
}
// for Mozilla, Firefox, Opera, etc.
else {
text = (new XMLSerializer()).serializeToString(xml);
}
return text.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
.replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
};
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();

// Append '#' to the window location so "Back" returns to the selected tab
// after a redirect or a full page refresh (e.g. Views tab).

// However, note this general disclaimer about going back to previous tabs:
// http://docs.jquery.com/UI/API/1.8/Tabs#Back_button_and_bookmarking

$("#tabs").bind("tabsselect", function(event, ui) { window.location.hash = ui.tab.hash; });


$("a.textLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("a.utf8TextLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", beforeSend: function(req) { req.setRequestHeader("Accept", "text/plain;charset=UTF-8"); }, success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("form.textForm").submit(function(event) {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "foo", contentType: "text/plain", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#readForm").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "foo=bar&fruit=apple", contentType: "application/x-www-form-urlencoded", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeForm").click(function() {
var link = $(this);
$.ajax({ url: this.href, dataType: "text", beforeSend: function(req) { req.setRequestHeader("Accept", "application/x-www-form-urlencoded"); }, success: function(form) { MvcUtil.showSuccessResponse(form, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

$("form.readXmlForm").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><javaBean><foo>bar</foo><fruit>apple</fruit></javaBean>", contentType: "application/xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("a.writeXmlLink").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
if (!this.url.match(/\.xml$/)) {
req.setRequestHeader("Accept", "application/xml");
}
},
success: function(xml) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(xml), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("form.readJsonForm").submit(function() {
var form = $(this);
var button = form.children(":first");
var data = form.hasClass("invalid") ?
"{ \"foo\": \"bar\" }" :
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }";
$.ajax({ type: "POST", url: form.attr("action"), data: data, contentType: "application/json", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("a.writeJsonLink").click(function() {
var link = $(this);
$.ajax({ url: this.href,
beforeSend: function(req) {
if (!this.url.match(/\.json$/)) {
req.setRequestHeader("Accept", "application/json");
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});

$("#readAtom").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: '<?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"><title>My Atom feed</title></feed>', contentType: "application/atom+xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeAtom").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
req.setRequestHeader("Accept", "application/atom+xml");
},
success: function(feed) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(feed), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("#readRss").submit(function() {
var form = $(this);
var button = form.children(":first");
$.ajax({ type: "POST", url: form.attr("action"), data: '<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"><channel><title>My RSS feed</title></channel></rss>', contentType: "application/rss+xml", dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, button); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});

$("#writeRss").click(function() {
var link = $(this);
$.ajax({ url: link.attr("href"),
beforeSend: function(req) {
req.setRequestHeader("Accept", "application/rss+xml");
},
success: function(feed) {
MvcUtil.showSuccessResponse(MvcUtil.xmlencode(feed), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

$("#byHeader").click(function(){
var link = $(this);
$.ajax({ url: this.href, dataType: "text", beforeSend: function(req) { req.setRequestHeader("FooHeader", "foo"); }, success: function(form) { MvcUtil.showSuccessResponse(form, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});

});
</script>


Per quanto riguarda il menù a tab invece chi è ad implementarlo?

Sò che mi sono dilungato non poco ma essendo praticamente a 0 ho pensato di specificare tutto per bene

Grazie mille a tutti
Andrea

wingman87
14-11-2012, 14:27
diciamo che al momento mi basterebbe anche solo sapere quale di questi gestisca il comportamento AJAX che prevede: click sul link, ricevi HTTP Response, estrai messaggio di Hello Worrld dal body di tale response, modifica il DOM e visualizza messaggio accanto al link
Provo a spiegarti questo, dandoti un po' di infarinatura di jQuery.
Partiamo dal link:

<a id="simpleLink" class="textLink" href="<c:url value="/simple" />">GET /simple</a>

l'elemento link, ai fini dello script, ha un id, un class e un href.
Lo script inizia con la seguente istruzione:

$(document).ready(function() {

$() è il costruttore degli oggetti jQuery. Al costruttore principalmente puoi passare 3 cose diverse:
- un elemento del dom
- un selettore
- del codice html
Nel primo caso l'elemento del dom passato viene wrappato, nel secondo (più avanti c'è un esempio) il costruttore cerca nel dom della pagina gli elementi che soddisfano il selettore e li wrappa tutti, nel terzo caso viene generato un elemento sul momento (non viene "appeso" al dom della pagina però) e viene wrappato.

Ciò che ottieni alla fine è comunque uno o più elementi wrappati.
Su questi elementi puoi quindi invocare tutte le funzioni di jQuery. Ne esistono di vari tipi ma in generale ogni funzione invocata ha effetto su tutti gli elementi wrappati. Inoltre, quasi sempre, le funzioni jQuery restituiscono un altro (o lo stesso) oggetto jQuery, in modo da poter concatenare più invocazioni.
http://api.jquery.com/jQuery/

Tornando al codice:
$(document).ready(function() {
$(document) wrappa il dom e ready aggiunge un handler all'evento ready dell'oggetto wrappato. L'handler è la funzione parametro della ready.
http://api.jquery.com/ready/

Tra le altre cose nell'handler viene fatto questo:
$("a.textLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});
"a.textLink" è un selettore. I selettori jQuery funzionano a grandi linee come i selettori css ma hanno anche qualcosa di più.
http://api.jquery.com/category/selectors/
Quindi a.textLink seleziona tutti gli elementi a che hanno la class textLink.
Agli elementi selezionati viene assegnato un handler per l'evento click.
All'interno degli handler, la variabile this è riferita all'elemento del dom che ha scatenato il click. Il this non è wrappato, e la funzione showSuccessResponse richiede un oggetto jQuery (se ho letto bene) e quindi ecco spiegata l'istruzione seguente:
var link = $(this);
Infine viene evocata la funzione ajax la quale non agisce su un particolare elemento, quindi viene invocato direttamente su $
http://api.jquery.com/jQuery.ajax/
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
Il parametro di questa funzione è un oggetto (la sintassi è json) con i seguenti campi:
url: la url a cui effettuare la richiesta. link.attr("href") restituisce il valore dell'attributo href dell'elemento wrappato
dataType: il tipo di risposta previsto
success: un handler per la risposta (la richiesta avviene in modo asincrono se non specificato diversamente, vedi i possibili campi dell'oggetto nella documentazione)
error: un handler nel caso avvenga un errore

Vediamo quindi cosa accade nel success, viene richiamata la seguente funzione:

MvcUtil.showSuccessResponse = function (text, element) {
MvcUtil.showResponse("success", text, element);
};

La quale richiama quest'altra:

MvcUtil.showResponse = function(type, text, element) {
var responseElementId = element.attr("id") + "Response";
var responseElement = $("#" + responseElementId);
if (responseElement.length == 0) {
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
} else {
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
responseElement = $("#" + responseElementId);
}
responseElement.fadeIn("slow");
};

In questa funzione puoi notare il terzo tipo di costruttore:
$('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>')
Per sintetizzare, questa funzione cerca un elemento con id="ID_DEL_LINK"+"Response"
Se lo trova rimpiazza il suo html:
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
Se invece non lo trova lo crea e lo inietta dopo il link
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
Infine aggiunge un effetto grafico di fadein al responseElement:
responseElement.fadeIn("slow");
http://api.jquery.com/fadeIn/

e-commerce84
14-11-2012, 16:21
Provo a spiegarti questo, dandoti un po' di infarinatura di jQuery.
Partiamo dal link:

<a id="simpleLink" class="textLink" href="<c:url value="/simple" />">GET /simple</a>

l'elemento link, ai fini dello script, ha un id, un class e un href.
Lo script inizia con la seguente istruzione:

$(document).ready(function() {

$() è il costruttore degli oggetti jQuery. Al costruttore principalmente puoi passare 3 cose diverse:
- un elemento del dom
- un selettore
- del codice html
Nel primo caso l'elemento del dom passato viene wrappato, nel secondo (più avanti c'è un esempio) il costruttore cerca nel dom della pagina gli elementi che soddisfano il selettore e li wrappa tutti, nel terzo caso viene generato un elemento sul momento (non viene "appeso" al dom della pagina però) e viene wrappato.

Ciò che ottieni alla fine è comunque uno o più elementi wrappati.
Su questi elementi puoi quindi invocare tutte le funzioni di jQuery. Ne esistono di vari tipi ma in generale ogni funzione invocata ha effetto su tutti gli elementi wrappati. Inoltre, quasi sempre, le funzioni jQuery restituiscono un altro (o lo stesso) oggetto jQuery, in modo da poter concatenare più invocazioni.
http://api.jquery.com/jQuery/

Tornando al codice:
$(document).ready(function() {
$(document) wrappa il dom e ready aggiunge un handler all'evento ready dell'oggetto wrappato. L'handler è la funzione parametro della ready.
http://api.jquery.com/ready/

Tra le altre cose nell'handler viene fatto questo:
$("a.textLink").click(function(){
var link = $(this);
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
return false;
});
"a.textLink" è un selettore. I selettori jQuery funzionano a grandi linee come i selettori css ma hanno anche qualcosa di più.
http://api.jquery.com/category/selectors/
Quindi a.textLink seleziona tutti gli elementi a che hanno la class textLink.
Agli elementi selezionati viene assegnato un handler per l'evento click.
All'interno degli handler, la variabile this è riferita all'elemento del dom che ha scatenato il click. Il this non è wrappato, e la funzione showSuccessResponse richiede un oggetto jQuery (se ho letto bene) e quindi ecco spiegata l'istruzione seguente:
var link = $(this);
Infine viene evocata la funzione ajax la quale non agisce su un particolare elemento, quindi viene invocato direttamente su $
http://api.jquery.com/jQuery.ajax/
$.ajax({ url: link.attr("href"), dataType: "text", success: function(text) { MvcUtil.showSuccessResponse(text, link); }, error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, link); }});
Il parametro di questa funzione è un oggetto (la sintassi è json) con i seguenti campi:
url: la url a cui effettuare la richiesta. link.attr("href") restituisce il valore dell'attributo href dell'elemento wrappato
dataType: il tipo di risposta previsto
success: un handler per la risposta (la richiesta avviene in modo asincrono se non specificato diversamente, vedi i possibili campi dell'oggetto nella documentazione)
error: un handler nel caso avvenga un errore

Vediamo quindi cosa accade nel success, viene richiamata la seguente funzione:

MvcUtil.showSuccessResponse = function (text, element) {
MvcUtil.showResponse("success", text, element);
};

La quale richiama quest'altra:

MvcUtil.showResponse = function(type, text, element) {
var responseElementId = element.attr("id") + "Response";
var responseElement = $("#" + responseElementId);
if (responseElement.length == 0) {
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
} else {
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
responseElement = $("#" + responseElementId);
}
responseElement.fadeIn("slow");
};

In questa funzione puoi notare il terzo tipo di costruttore:
$('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>')
Per sintetizzare, questa funzione cerca un elemento con id="ID_DEL_LINK"+"Response"
Se lo trova rimpiazza il suo html:
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
Se invece non lo trova lo crea e lo inietta dopo il link
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
Infine aggiunge un effetto grafico di fadein al responseElement:
responseElement.fadeIn("slow");
http://api.jquery.com/fadeIn/

Ti ringrazio, sei stato estremamente gentile...vedrò di approfondire l'argomento che può sempre tornare utile :-)

Secondo te dovrei iniziare per forza con JavaScript o posso iniziare direttamente a studiare JQuery?

wingman87
14-11-2012, 19:19
Io ho iniziato con il tutorial di javascript di w3schools:
http://www.w3schools.com/js/default.asp
Il linguaggio non è complesso, il tutorial lo leggi in un paio d'ore o poco più.

Poi per imparare jQuery un mio collega mi ha dato un'infarinatura, un po' come ho fatto io nel mio post precedente, e per il resto mi sono informato sul sito ufficiale e cercando su internet mano a mano che avevo nuove necessità.

Però mi rendo conto che questo approccio funziona se sai quello che vuoi fare, se invece vuoi solo imparare forse è meglio un buon libro, però al riguardo non so consigliarti...

e-commerce84
16-11-2012, 15:31
Ciao,
intanto ti ringrazio ancora per la tua più che chiara spiegazione. In questi giorni mi sono dato una studiata alle basi di JQuery ed ho iniziato a capirci qualcosa...diciamo che non sarei ancora in grado di scrivere dei miei script ma almeno a capirci qualcosa di roba già scritta si...

Ti vorrei fare un altro paio di domande però:

1) Ho notato che per come era scritto il codice in quel sorgente che ti postai mi risultava molto oscuro interpretarlo, così ho provato a riorganizzarlo (più che altro mettendomelo su più linee dividendolo in "blocchi" logici), ho fatto così:


<script>
MvcUtil = {};

// Handler caso di successo:
MvcUtil.showSuccessResponse = function (text, element) {
// Invoca la funzione showResponse passandogli: 1) Stringa "success", il messaggio ricevuto, l'id del link che ha generato la chiamata
MvcUtil.showResponse("success", text, element);
};
MvcUtil.showErrorResponse = function showErrorResponse(text, element) {
MvcUtil.showResponse("error", text, element);
};

/* Handler della gestionre dei vari casi possibili, riceve in input: 1) type=success\error, il testo ricevuto, l'elemento che ha generato
l'evento click */
MvcUtil.showResponse = function(type, text, element) {
var responseElementId = element.attr("id") + "Response"; // Estrae l'id del link clickato e lo concatena con la stringa "Response"

// Cerca un elemento avente id = ID_DEL_LINK"+"Response" (lo span dove và a mettere il testo)
var responseElement = $("#" + responseElementId);
if (responseElement.length == 0) { // Se non lo trova, allora lo crea e lo appende DOPO il link (referenziato da element)
responseElement = $('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>').insertAfter(element);
} else { // Se invece lo trova, rimpiazza il suo contenuto HTML
responseElement.replaceWith('<span id="' + responseElementId + '" class="' + type + '" style="display:none">' + text + '</span>');
responseElement = $("#" + responseElementId);
}
responseElement.fadeIn("slow"); // Aggiunge un effetto grafico di fadein al responseElement
};

//......
// ALTRA ROBA NON ANCORA ANALIZZATA
//...
</script>

<script type="text/javascript">

$(document).ready(function() { // Wrappa la root del DOM e gli aggiunge una funzione che sarà eseguita quando il DOM è pronto (evento ready)
$("#tabs").tabs();

// Append '#' to the window location so "Back" returns to the selected tab
// after a redirect or a full page refresh (e.g. Views tab).

// However, note this general disclaimer about going back to previous tabs:
// http://docs.jquery.com/UI/API/1.8/Tabs#Back_button_and_bookmarking

$("#tabs").bind("tabsselect", function(event, ui) { window.location.hash = ui.tab.hash; });

// Seleziona tutti i link aventi classe "textLink" e definisce una funzione di call back al verificarsi dell'evento click su uno di questi link
$("a.textLink").click(function(){
var link = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento (il link che è stato clickato)

/* La chiamata AJAX non viene invocata su un oggetto particolare (quindi direttamente su $)
Il parametro di input della funzione ajax è un oggetto con sintassi JSON al cui interno trovo: link.attr("href") restituisce il valore
dell'attributo href (l'indirizzo del link) dell'elemento wrappato. dataType: il tipo di risposta previsto */
$.ajax({ url: link.attr("href"), dataType: "text",
success: function(text) { // In caso di successo: chiama un handler per il caso di successo
// Passa a tale handler il testo ritornato ed il riferimento al link che ha generato l'evento
MvcUtil.showSuccessResponse(text, link);
},
error: function(xhr) { // In caso di insuccesso:
MvcUtil.showErrorResponse(xhr.responseText, link);
}
});
return false;
});

//......
// ALTRA ROBA NON ANCORA ANALIZZATA
//...
</script>


(ho tolto le porzioni di codice che non ho ancora esaminato, mi sono limitato alle cose di cui avevamo parlato l'altra volta)

Forse è una domanda stupida ma secondo te è meglio organizzarselo così o aveva un suo senso il fatto di tenerlo compresso in meno righe? a me sembrava veramente brutto e poco leggibile...una volta che lo ho riorganizzato così mi son trovato anche meglio ad interpretarlo e a cercare online il significato delle varie funzioni usate...

2) Attualmente non sò NULLA di JSON (sò solo che è un sistema di comunicazione dati alternativo all'XML), prima o poi me lo vedrò...attualmente mi potresti confermare o smentire il fatto che quando fà la chiamata AJAX, in questo modo:

$.ajax({ url: link.attr("href"), dataType: "text"

il "client" si aspetta di ricevere una stringa testuale DENTRO il BODY della HTTP RESPONSE inviata dal business?

Grazie mille
Andrea

wingman87
16-11-2012, 20:13
Forse è una domanda stupida ma secondo te è meglio organizzarselo così o aveva un suo senso il fatto di tenerlo compresso in meno righe? a me sembrava veramente brutto e poco leggibile...una volta che lo ho riorganizzato così mi son trovato anche meglio ad interpretarlo e a cercare online il significato delle varie funzioni usate...

Il fatto che ti trovi meglio così è già una risposta :D
Ovviamente per chi è pratico la maggior parte dei commenti sono ridondanti, però ad esempio indentare il codice su più righe è una cosa che tendo a fare sempre anch'io...
Al di là del fattore soggettivo, a quanto ne so comprimere il codice può servire solo a trasmettere meno e/o ad offuscare il codice (che non dovrebbe mai essere una necessità nel codice lato client).

2) Attualmente non sò NULLA di JSON (sò solo che è un sistema di comunicazione dati alternativo all'XML), prima o poi me lo vedrò...attualmente mi potresti confermare o smentire il fatto che quando fà la chiamata AJAX, in questo modo:

$.ajax({ url: link.attr("href"), dataType: "text"

il "client" si aspetta di ricevere una stringa testuale DENTRO il BODY della HTTP RESPONSE inviata dal business?

Confermo, sulla documentazione della funzione ajax trovi anche gli altri dataType supportati. Cambiando il dataType dovrai andare anche a cambiare il ContentType della Response, se necessario, lato server.