Ajax Prima Parte!!
Ajax: tutti conoscono quest’acronimo ormai, la tecnologia mostrata al mondo da Google ma inventata non si sa bene da chi (Microsoft forse
() sta riscuotendo grande notorietà. Ajax riesce infatti in modo non troppo complesso ad eliminare tutte le problematiche di gestione dei dati client-server, rendendo le WebApplication sempre più simile alle classiche applicazioni desktop side. Andiamo dunque a vedere un piccolo esempio di come la tecnologia funziona, Ajax utilizza il linguaggio JavaScript di Netscape per la programmazione lato client e si appoggia ad uno qualsiasi dei framework lato server (JSP-ASP-ASP.NET-PHP etc). Nell’esempio verrà utilizzato il framework JSP-Servlet che io conosco meglio
. In questo piccolo frammento di codice usiamo Ajax per inserire e farci restituire una stringa di testo senza la necessità di dover ricaricare la pagina!!!!
CODICE LATO CLIENT
<!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>INVIO DI DATI Tramite Ajax</title>
<script type=”text/javascript”>
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”); //creo l’oggetto XMLHttpREquest
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createQueryString() {
var firstName = document.getElementById(“firstName”).value;
var middleName = document.getElementById(“middleName”).value;
var birthday = document.getElementById(“birthday”).value;
var queryString = “firstName=” + firstName + “&middleName=” + middleName
+ “&birthday=” + birthday;
return queryString;
}
function doRequestUsingGET() {
createXMLHttpRequest();
var queryString = “GetAndPostExample?”;
queryString = queryString + createQueryString()
+ “&timeStamp=” + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange; //gestisco lo stato di XMLHttpRequest nel Get
xmlHttp.open(“GET”, queryString, true);
xmlHttp.send(null);
}
function doRequestUsingPOST() {
createXMLHttpRequest();
var url = “GetAndPostExample?timeStamp=” + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open(“POST”, url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
xmlHttp.send(queryString);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById(“serverResponse”);
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
</script>
</head>
<body>
<h1>Inserisci il tuo nome, cognome e data di nascita:</h1>
<table>
<tbody>
<tr>
<td>Nome:</td>
<td><input type=”text” id=”firstName”/>
</tr>
<tr>
<td>Cognome:</td>
<td><input type=”text” id=”middleName”/>
</tr>
<tr>
<td>Data di Nascita:</td>
<td><input type=”text” id=”birthday”/>
</tr>
</tbody>
</table>
<form action=”#”>
<input type=”button” value=”Send parameters using GET” onclick=”doRequestUsingGET();”/>
<br/><br/>
<input type=”button” value=”Send parameters using POST” onclick=”doRequestUsingPOST();”/>
</form>
<br/>
<h2>Server Response:</h2>
<div id=”serverResponse”></div>
</body>
</html>
CODICE LATO SERVER “SERVLET”
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetAndPostExample extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response, String method)
throws ServletException, IOException {
//Set content type of the response to text/xml
response.setContentType(“text/xml“); // invio dati in formato XML
//Get the user’s input
String firstName = request.getParameter(“firstName”);
String middleName = request.getParameter(“middleName”);
String birthday = request.getParameter(“birthday”);
//Create the response text
String responseText = “Hello ” + firstName + ” ” + middleName
+ “. Your birthday is ” + birthday + “.”
+ ” [Method: " + method + "]“;
//Write the response back to the browser
PrintWriter out = response.getWriter();
out.println(responseText);
//Close the writer
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, “GET”);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, “POST”);
}
}
Il codice è molto semplice e di facile comprensione, spero che il piccolo esempio possa far capire a tutti che Ajax è un paradigma di programmazione Web di facile comprensione, ma che apre scenari, davvero interessanti nel mondo delle Applicazioni Web.
Good Code Folks
)
il tuo esempio è fantastico, in pochissimi passi ho compreso quello che 10 siti e altrettanti libri non mi hanno spiegato.
Continuate cosi.
Grazie ancora