I am trying out some AJAX code, where an HTML page makes an ajax call to a JSP page and gets the date from the JSP to present on the HTML page. The code below just shows the entire reponse in the alert box, and all I get in return is a random number like this :1334754128581. The responsetext is not returning the HTML. The code does return a readystate of 4 and status == 200. Here’s the code in the HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<script type="text/javascript">
function createXMLHttpRequest(){
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
return new XMLHttpRequest();
}
var AJAX = createXMLHttpRequest();
function handler() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
var txt = AJAX.responseText ;
alert('Ajax success. Result: ' + txt);
}else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Ajax failed');
}
}
function show(){
AJAX.open("GET", "service.jsp");
AJAX.onreadystatechange = handler;
AJAX.send("");
};
</script>
<body>
<a href="#" onclick="javascript:show();"> Click to get data from server</a>
</body>
</html>
The JSP page:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<title> JSP </title>
</head>
<body>
<%=new java.util.Date()%>
</body>
</html>
This code is being run on Tomcat v7.
Sorry, my mistake. I had a custom servlet in web.xml that was processing all jsps. The servlet writes current time to the writer that is where I was getting the random number from.