CORSO DI TECNOLOGIE E APPLICAZIONI WEB

Transcript

CORSO DI TECNOLOGIE E APPLICAZIONI WEB
Università degli Studi di Modena e Reggio Emilia
Facoltà di Ingegneria – Reggio Emilia
CORSO DI
TECNOLOGIE E APPLICAZIONI WEB
AJAX
(Asynchronous JavaScript and XML)
Ing. Marco Mamei
M. Mamei - Tecnologie e Applicazioni Web
1
Pagine Web Interattive e Dinamiche
Nelle lezioni precedenti, abbiamo visto diversi meccanismi per
rendere interattive e dinamiche le pagine Web (JavaScript, JSP,
etc.).
Questi meccanisi sono molto flessibili e potenti, tuttavia soffrono
di notevoli problemi di performance. Le applicazioni desktop
offrono una ricchezza e una reattività molto maggiore.
Il motivo alla base di questi problemi di performance è facilmente
individuabile nelle ripetute interazioni tra client e server (queste
rappresentano il collo di bottiglia del sistema).
Ci sono tuttavia alcuni contro-esempi che vale la pena di
investigare.
• Google Suggest (http://www.google.com/webhp?complete=1&hl=en) è un
servizio di Google che fornisce suggerimenti per la ricerca
man mano che una richiesta viene digitata. Le performance di
questo sistema sono ottime – i suggerimenti arrivano mentre
si digita in tempo reale.
• Google Maps (http://maps.google.com/) permette di zommare e
scrollare la mappa del mondo. Anche in questo caso con
un’ottima velocità
È chiaro che in entrambi questi servizi il browser interagisce con il
server per scaricare informazioni (suggerimenti, o nuovi pezzi
della mappa) , tuttavia l’interazione è dinamica (non basata su
form esplicite), inoltre non bisogna ricaricare e ridisegnare la
pagina ad ogni interazione – a tutto vantaggio della velocità…
M. Mamei - Tecnologie e Applicazioni Web
2
Applicazioni web classiche
The classic web application model works like this: Most user actions in the interface trigger an
HTTP request back to a web server. The server does some processing — retrieving data,
crunching numbers, talking to various legacy systems — and then returns an HTML page to the
client.
This approach doesn’t make for a great user experience. While the server is doing its thing,
what’s the user doing? That’s right, waiting. And at every step in a task, the user waits some
more.
Obviously, if we were designing the Web from scratch for applications, we wouldn’t make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? In fact, why should the user see the
application go to the server at all?
Applicazioni Web AJAX
L’idea alla base di AJAX è quella di creare una serie di funzioni
javascript che accedono al server in modo asincrono, lasciando
all’utente la possibilità di interagire con l’applicazione.
M. Mamei - Tecnologie e Applicazioni Web
3
Performance
Vediamo come l’introduzione dello strato javascript (AJAX) si
traduce in termini di prestazioni.
M. Mamei - Tecnologie e Applicazioni Web
4
Vediamo un po’ di Codice…
Per realizzare un’applicazione AJAX cosa dobbiamo imparare?
• Sappiamo già disegnare l’interfaccia (pagina web) di una
web application tramite HTML, XML, CSS, XSL, Javascript
• Dobbiamo imparare come si fa ad interrogare un server da
Javascript in modo asincrono
• Dobbiamo imparare a manipolare la risposta del server
(tipicamente in XML) proveniente dal server.
Come effettuare una richiesta HTTP da
Javascript.
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");}
catch (e) {}}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true); // first parameter can be ‘GET’ or ‘POST’
// second par is the url to be accessed
// third say asynchronous yes or no
http_request.send(null);
// in case of POST the parameters are set
// like: name=value&name=value&name=value
}
M. Mamei - Tecnologie e Applicazioni Web
5
Come processare la risposta
Analizzare la risposta come file di testo
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
}
else {
alert('There was a problem with the request.');
}
}
}
Analizzare la risposta come XML. Accediamo al XML tramite il
DOM!!!!
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.childNodes[0].data);
}
else {
alert('There was a problem with the request.');
}
}
}
M. Mamei - Tecnologie e Applicazioni Web
6
Esempio Completo
File html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="ajax-xml.js"></script>
</head>
<body>
<span style="cursor: pointer; text-decoration: underline"
onclick="makeRequest('test.xml')">
Make a request
</span>
</body>
</html>
File XML sul server
<?xml version="1.0"?>
<root>
Hello Ajax XML
</root>
M. Mamei - Tecnologie e Applicazioni Web
7
Esempio Completo
File Javascript
var http_request = false;
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");}
catch (e) {}}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.childNodes[0].data);
}
else {
alert('There was a problem with the request.');
}
}
}
M. Mamei - Tecnologie e Applicazioni Web
8