Magazine
 
Quick Review:Ajax
 
Ajax Examples
 

String pass = “root”;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery(“SELECT * FROM users where
user_name=’”+username+”’”);
StringBuffer responseXML = new StringBuffer();
responseXML.append(“<?xml version=\”1.0\” encoding=\”ISO-8859-1\”?>”);
responseXML.append(“<user>”);
while (res.next()) {
String un = res.getString(“user_name”);
String fn = res.getString(“first_name”);
String ln = res.getString(“last_name”);
responseXML.append(“<user_name>”+un+”</user_name>”);
responseXML.append(“<first_name>”+fn+”</first_name>”);
responseXML.append(“<last_name>”+ln+”</last_name>”);
}
responseXML.append(“</user>”);
response.getWriter().write(responseXML.toString());
con.close();
}
catch (SQLException s){
System.out.println(“SQL code does not execute.”);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

This servlet sends the response in XML format. Now after getting the response back the JavaScript function “callback ()” is called to work on server response data.

if( xmlHttp.readyState==4 ){
if( xmlHttp.status==200 ) {
xmlDoc=xmlHttp.responseXML;
document.getElementById(“firstname”).innerHTML=
xmlDoc.getElementsByTagName(“first_name”)[0].childNodes[0].nodeValue;
document.getElementById(“lastname”).innerHTML=
xmlDoc.getElementsByTagName(“last_name”)[0].childNodes[0].nodeValue;
}
}

 Apr 2008 | Java Jazz Up |26
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78,   Download PDF