Visualizzazione dei risultati da 1 a 5 su 5
  1. #1

    [JQuery ?!?] Da dove iniziare per capire questo esempio?

    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:



    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-s...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 (lo ho linkato perchè è lunghetto e non me lo fà inserire all'interno del post): http://andreanobiliphoto.com/storage/java/home.jsp

    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:

    codice:
    [*]
    				">GET /simple
    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:

    codice:
    <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>

  2. #2
    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:

    codice:
    <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/Ta...nd_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

  3. #3
    Utente di HTML.it
    Registrato dal
    Dec 2010
    Messaggi
    3,660
    stai importando jquery ed alcuni plugin basati su jquery, tra questi plugin c'è jquery.ui.tabs.js che gestisce il menu in alto, poi c'è altro codice js che si occupa, tra le altre cose, di effettuare chiamate ajax, la funzione che viene chiamata quando si clicca il link è questa:

    codice:
    $("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;
    	});
    Leggi i tutorials che trovi sul sito, e studiati le api, secondo me devi vederti almeno i seguenti argomenti:

    Selectors
    Attributes
    Traversing
    Manipulation
    Events
    Forms
    Ajax


  4. #4
    Originariamente inviato da Vindav
    stai importando jquery ed alcuni plugin basati su jquery, tra questi plugin c'è jquery.ui.tabs.js che gestisce il menu in alto, poi c'è altro codice js che si occupa, tra le altre cose, di effettuare chiamate ajax, la funzione che viene chiamata quando si clicca il link è questa:

    codice:
    $("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;
    	});
    Leggi i tutorials che trovi sul sito, e studiati le api, secondo me devi vederti almeno i seguenti argomenti:

    Selectors
    Attributes
    Traversing
    Manipulation
    Events
    Forms
    Ajax

    Grazie mille, provvederò

  5. #5
    ahhh ma secondo te posso iniziare a studiarmi direttamente JQuery o devo iniziare per forza con JavaScript?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.