Reputation: 2101
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.
Upvotes: 2
Views: 2424
Reputation: 2101
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.
Upvotes: 1
Reputation: 14877
I have tested on Tomcat 6 and it is working fine.
You are asking for a complete web page with your Ajax call, and you're getting one back. It's working as designed, as they say. The problem is not with your Ajax, but with what you are returning from the server. You should be returning the output only not a web page that happens to have output.
In your case, it should be only <%=new java.util.Date()%>
if you want to return current date.
Upvotes: 1