
How can we fetch data in ajax through servlet?

"mainpage.jsp"
<html>
<head>
<title>Ajax Example</title>
<script language="Javascript">
function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
function showCurrentTime(){
var rnd = Math.random();
var url="showTime";
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>
"MyServletAjax.java"
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServletAjax extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
Date date = new Date();
PrintWriter pw = response.getWriter();
pw.println(date);
}
}
"web.xml"
<servlet> <servlet-name>myservletajax</servlet-name> <servlet-class>MyServletAjax</servlet-class> </servlet> <servlet-mapping> <servlet-name>myservletajax</servlet-name> <url-pattern>/myServletAjax</url-pattern> </servlet-mapping>
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.