sabato 14 luglio 2007

Semplice esempio di richiesta

L'esempio descrive una pagina HTML che contiene il pulsante "Invia richiesta asincrona al server".
Cliccando sul pulsante si avvia appunto una richiesta asincrona al server.
Il server risponde inviando un file di testo statico XML contenete la seguente stringa “Hello AJAX world”.
La risposta viene gestita dal browser mostrando il contenuto del file XML in una finestra di avviso mediante il comando alert.

Link all'esempio eseguibile.



Codice della pagina HTML interpretato dal browser

<!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>
<title>Simple XMLHttpRequest</title>

<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "simpleResponse.xml", true);
xmlHttp.send(null);
}

function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
alert("Risposta dal server: " + xmlHttp.responseText);
}
}
}
</script>
</head>

<body>
<form action="#">
<input type="button" value="Invia richiesta asincrona al server" onclick="startRequest();"/>
</form>
</body>
</html>



File simpleResponse.xml presente sul server


Hello AJAX world

Nessun commento: