Wednesday, April 22, 2009

Ajax Simple Example to call Servlet

<html>
<head>

<title>Ajax Example</title>

<script language="Javascript">

function postRequest(strURL) {

var xmlHttp;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...

xmlHttp = new XMLHttpRequest();

} else if (window.ActiveXObject) { // IE

try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}

}

xmlHttp.open('POST', strURL, true);

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xmlHttp.onreadystatechange = function() {

if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

updatepage(xmlHttp.responseText);

}

}

xmlHttp.send(strURL);

}


function updatepage(str){

//for more than one data use
// var arr = str.split(“separator symbol”);
// for(var i = 0;i<arr.length();i++)
//{
// get the data arr[i] and place it in page using //object.innerHTML = arr[i];
//}


document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;

}

function showCurrentTime(){

var rnd = Math.random();

var url="servlet_url?id="+rnd;

postRequest(url);

}

</script>

</head>

<body>

<h1 align="center"><font color="#000080">Ajax Example</font></h1>

<p><font color="#000080"> This very simple Ajax Example retrieves the

current date and time from server and shows on the form. To view the current

date and time click on the following button.</font></p>

<form name="f1">

<p align="center"><font color="#000080"> <input value=" Show Time "
type="button" onclick='JavaScript:showCurrentTime()' name="showdate"></font></p>

<div id="result" align="center"></div>

</form>

<div id=result></div>

</body>

</html>

.................................
Servlet coding.

just print the response data using out.println("data"+"separator symbol");

No comments:

Post a Comment