e-commerce84
27-11-2012, 16:41
Ciao a tutti,
stò incontrando notevoli difficoltà a capire il funzionamento di un metodo appartenente ad uno script JQuery di un esempio di showcase che stò studiando in questo periodo (è lo showcase di Spring MVC, un framwork MVC Java, ma in questo caso Spring e Java non c'entrano molto...il problema è che non capisco alcune cose di JQuery)
In pratica ho una view home.jsp che al suo interno contiene il seguente link:
<li>
<a id="byProducesAcceptJson" class="writeJsonLink" href="<c:url value="/mapping/produces" />">By produces via Accept=application/json</a>
</li>
Tale link genera una richiesta HTTP verso una specifica cartella all'interno della mia web app ("/mapping/produces").
Questo link ha classe writeJsonLink alla quale è associata una funzione di callback JQuery per l'evento di click.
Posto TUTTO lo script JQuery (perchè a questo punto visto che mi sfugge qualcosa non vorrei che chiamasse in qualche modo strano qualche altra funzione e non me ne sono accorto)
<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 = {};
// 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\E0 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
};
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() { // Wrappa la root del DOM e gli aggiunge una funzione che sar\E0 eseguita quando il DOM \E8 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 \E8 stato clickato)
/* La chiamata AJAX non viene invocata su un oggetto particolare (quindi direttamente su $)
Il parametro di input della funzione ajax \E8 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;
});
$("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;
});
// Seleziona il form avente classe "readJsonForm" e gli assegna la seguente funzione di callback per l'evento submit
$("form.readJsonForm").submit(function() {
var form = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento submit (il form)
var button = form.children(":first"); // Seleziona il bottone submit
var data = form.hasClass("invalid") ? // OPERATORE CONDIZIONALE: il form ha classe "invalid" ?
"{ \"foo\": \"bar\" }" : // SI: foo = bar
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }"; // NO: foo= bar ; fruit = apple
/* AJAX CALL PARAMETER:
type: Say to the servlet tath the request is a POST HTTP Request
url: The address to which to send the call
data: the content of my data variable
contentType: an object having JSON format
dataType: the type of content returned by the server
*/
$.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;
});
/* Seleziona i link aventi classe writeJsonLink e gli assegna la seguente funzione di callback per l'evento click */
$("a.writeJsonLink").click(function() {
var link = $(this); // Variabile che si riferisce all'elemento del DOM che ha scatenato l'evento click (il link clickato)
// Esegue la chiamata ajax
$.ajax({
url: this.href, // Indirizzo verso cui è indirizzata la richiesta
beforeSend: function(req) { // Prima di inviare l'HTTP Request esegui la funzione passandogli il parametro req
if (!this.url.match(/\.json$/)) { // Se l'url termina con .json
req.setRequestHeader("Accept", "application/json"); // Aggiunge alla HTTP Request l'header 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(){ // Seleziona il link avente id="byHeader" e gli assegna la seguente funzione di callback per l'evento click
var link = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento (il link che \E8 stato clickato)
/* La chiamata AJAX non viene invocata su un oggetto particolare (quindi direttamente su $)
I parametri di input sono: 1) L'URL del link selezionato 2) Il tipo di risposta previso (una stringa)
*/
$.ajax({ url: this.href, dataType: "text",
// Prima di inviare l'HTTP Request esegui la funzione che aggiunge un Header alla richiesta HTTP
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>
A questo punto, per l'evento di click sul link avente classe writeJsonLink dovrebbe essere associata SOLO la seguente funzione del precedente script:
/* Seleziona i link aventi classe writeJsonLink e gli assegna la seguente funzione di callback per l'evento click */
$("a.writeJsonLink").click(function() {
var link = $(this); // Variabile che si riferisce all'elemento del DOM che ha scatenato l'evento click (il link clickato)
// Esegue la chiamata ajax
$.ajax({
url: this.href, // Indirizzo verso cui è indirizzata la richiesta
beforeSend: function(req) { // Prima di inviare l'HTTP Request esegui la funzione passandogli il parametro req
if (!this.url.match(/\.json$/)) { // Se l'url termina con .json
req.setRequestHeader("Accept", "application/json"); // Aggiunge alla HTTP Request l'header Accept: application/json
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});
Da quello che ho capito analizzandola (conosco ben poco JQuery) dovrebbe funzionare così:
1) Quando clicko sul link parte la funzione
2) Prima di inviare la chiamata AJAX all'url di destinazione (il mio controller) controlla se l'url termina con l'estensione .json e se vi termina mette negli header della HTTP Request un nuovo header avente forma: "Accept", "application/json". In questo caso questa operazione NON VIENE FATTA (almeno credo...) in quanto il mio url non termina con .json ma è una directory ("/mapping/produces")
3) A questo punto se la chiamata AJAX ha avuto successo invoca il metodo MvcUtil.showSuccessResponse del mio script passandogli la versione convertita in stringa di un oggetto chiamato json e l'url.
Quello che fà il metodo showSuccessResponse() è molto semplice...come potete vedere dal codice completo semplicemente richiama un altro metodo JQuery che crea uno span contenente un messaggio di output che andrà a visualizzare accanto al link che è stato clickato...
Ora quà iniziano i miei dubbi e le cose che non riesco proprio a capire: quando nella mia funzione faccio:
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
Ok json è un parametro di input della function che viene chiamata nel caso che la chiamata AJAX abbia avuto successo...in pratica credo che gli stò passando un oggetto JSON json a tale funzione...ma chi cavolo l'ha creato questo oggetto ?!?! Tra l'altro poi passo tale oggetto json convertito a stringa al metodo showSuccessResponse che appunto si occuperà di mostrarmi questa stringa accanto al link che è stato clickato
Di fatto se clicko il link, accanto ad esso poi mi appare il messaggio: {"foo":"bar","fruit":"apple"}
Sembra come se da qualche parte fosse stato creato un "oggetto" JSON che contiene i seguenti record key\value:
foo: bar
fruit: apple
Ma dove sarebbero stati creati? chi li crea? la cosa mi sfugge...anche perchè il metodo controller Java che si occupa di gestire la richiesta HTTP che si genera clickando quel link è un semplicissimo metodo che semplicemente gestisce solo HTTP Request di tipo GET e che si aspetta di ricevere in INPUT un oggetto JSON che converte in un JavaBean (quindi in un oggetto che contiene i campi contenuti nell'oggetto JSON che gli arriva in input)...in pratica questo metodo non costruisce l'oggetto ma si aspetta di riceverlo in input...quindi per forza di cose l'oggetto JSON che gli viene passato deve essere creato in qualche modo nella view di prima...questo è la cosa che non capisco !!!
@RequestMapping(value="/mapping/produces", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody JavaBean byProducesJson() {
return new JavaBean();
}
C'è qualcuno in grado di aiutarmi a risolvere questo mistero? :dhò: :dhò: :dhò:
Grazie mille
Andrea
stò incontrando notevoli difficoltà a capire il funzionamento di un metodo appartenente ad uno script JQuery di un esempio di showcase che stò studiando in questo periodo (è lo showcase di Spring MVC, un framwork MVC Java, ma in questo caso Spring e Java non c'entrano molto...il problema è che non capisco alcune cose di JQuery)
In pratica ho una view home.jsp che al suo interno contiene il seguente link:
<li>
<a id="byProducesAcceptJson" class="writeJsonLink" href="<c:url value="/mapping/produces" />">By produces via Accept=application/json</a>
</li>
Tale link genera una richiesta HTTP verso una specifica cartella all'interno della mia web app ("/mapping/produces").
Questo link ha classe writeJsonLink alla quale è associata una funzione di callback JQuery per l'evento di click.
Posto TUTTO lo script JQuery (perchè a questo punto visto che mi sfugge qualcosa non vorrei che chiamasse in qualche modo strano qualche altra funzione e non me ne sono accorto)
<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 = {};
// 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\E0 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
};
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() { // Wrappa la root del DOM e gli aggiunge una funzione che sar\E0 eseguita quando il DOM \E8 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 \E8 stato clickato)
/* La chiamata AJAX non viene invocata su un oggetto particolare (quindi direttamente su $)
Il parametro di input della funzione ajax \E8 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;
});
$("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;
});
// Seleziona il form avente classe "readJsonForm" e gli assegna la seguente funzione di callback per l'evento submit
$("form.readJsonForm").submit(function() {
var form = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento submit (il form)
var button = form.children(":first"); // Seleziona il bottone submit
var data = form.hasClass("invalid") ? // OPERATORE CONDIZIONALE: il form ha classe "invalid" ?
"{ \"foo\": \"bar\" }" : // SI: foo = bar
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }"; // NO: foo= bar ; fruit = apple
/* AJAX CALL PARAMETER:
type: Say to the servlet tath the request is a POST HTTP Request
url: The address to which to send the call
data: the content of my data variable
contentType: an object having JSON format
dataType: the type of content returned by the server
*/
$.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;
});
/* Seleziona i link aventi classe writeJsonLink e gli assegna la seguente funzione di callback per l'evento click */
$("a.writeJsonLink").click(function() {
var link = $(this); // Variabile che si riferisce all'elemento del DOM che ha scatenato l'evento click (il link clickato)
// Esegue la chiamata ajax
$.ajax({
url: this.href, // Indirizzo verso cui è indirizzata la richiesta
beforeSend: function(req) { // Prima di inviare l'HTTP Request esegui la funzione passandogli il parametro req
if (!this.url.match(/\.json$/)) { // Se l'url termina con .json
req.setRequestHeader("Accept", "application/json"); // Aggiunge alla HTTP Request l'header 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(){ // Seleziona il link avente id="byHeader" e gli assegna la seguente funzione di callback per l'evento click
var link = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento (il link che \E8 stato clickato)
/* La chiamata AJAX non viene invocata su un oggetto particolare (quindi direttamente su $)
I parametri di input sono: 1) L'URL del link selezionato 2) Il tipo di risposta previso (una stringa)
*/
$.ajax({ url: this.href, dataType: "text",
// Prima di inviare l'HTTP Request esegui la funzione che aggiunge un Header alla richiesta HTTP
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>
A questo punto, per l'evento di click sul link avente classe writeJsonLink dovrebbe essere associata SOLO la seguente funzione del precedente script:
/* Seleziona i link aventi classe writeJsonLink e gli assegna la seguente funzione di callback per l'evento click */
$("a.writeJsonLink").click(function() {
var link = $(this); // Variabile che si riferisce all'elemento del DOM che ha scatenato l'evento click (il link clickato)
// Esegue la chiamata ajax
$.ajax({
url: this.href, // Indirizzo verso cui è indirizzata la richiesta
beforeSend: function(req) { // Prima di inviare l'HTTP Request esegui la funzione passandogli il parametro req
if (!this.url.match(/\.json$/)) { // Se l'url termina con .json
req.setRequestHeader("Accept", "application/json"); // Aggiunge alla HTTP Request l'header Accept: application/json
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});
Da quello che ho capito analizzandola (conosco ben poco JQuery) dovrebbe funzionare così:
1) Quando clicko sul link parte la funzione
2) Prima di inviare la chiamata AJAX all'url di destinazione (il mio controller) controlla se l'url termina con l'estensione .json e se vi termina mette negli header della HTTP Request un nuovo header avente forma: "Accept", "application/json". In questo caso questa operazione NON VIENE FATTA (almeno credo...) in quanto il mio url non termina con .json ma è una directory ("/mapping/produces")
3) A questo punto se la chiamata AJAX ha avuto successo invoca il metodo MvcUtil.showSuccessResponse del mio script passandogli la versione convertita in stringa di un oggetto chiamato json e l'url.
Quello che fà il metodo showSuccessResponse() è molto semplice...come potete vedere dal codice completo semplicemente richiama un altro metodo JQuery che crea uno span contenente un messaggio di output che andrà a visualizzare accanto al link che è stato clickato...
Ora quà iniziano i miei dubbi e le cose che non riesco proprio a capire: quando nella mia funzione faccio:
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
Ok json è un parametro di input della function che viene chiamata nel caso che la chiamata AJAX abbia avuto successo...in pratica credo che gli stò passando un oggetto JSON json a tale funzione...ma chi cavolo l'ha creato questo oggetto ?!?! Tra l'altro poi passo tale oggetto json convertito a stringa al metodo showSuccessResponse che appunto si occuperà di mostrarmi questa stringa accanto al link che è stato clickato
Di fatto se clicko il link, accanto ad esso poi mi appare il messaggio: {"foo":"bar","fruit":"apple"}
Sembra come se da qualche parte fosse stato creato un "oggetto" JSON che contiene i seguenti record key\value:
foo: bar
fruit: apple
Ma dove sarebbero stati creati? chi li crea? la cosa mi sfugge...anche perchè il metodo controller Java che si occupa di gestire la richiesta HTTP che si genera clickando quel link è un semplicissimo metodo che semplicemente gestisce solo HTTP Request di tipo GET e che si aspetta di ricevere in INPUT un oggetto JSON che converte in un JavaBean (quindi in un oggetto che contiene i campi contenuti nell'oggetto JSON che gli arriva in input)...in pratica questo metodo non costruisce l'oggetto ma si aspetta di riceverlo in input...quindi per forza di cose l'oggetto JSON che gli viene passato deve essere creato in qualche modo nella view di prima...questo è la cosa che non capisco !!!
@RequestMapping(value="/mapping/produces", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody JavaBean byProducesJson() {
return new JavaBean();
}
C'è qualcuno in grado di aiutarmi a risolvere questo mistero? :dhò: :dhò: :dhò:
Grazie mille
Andrea