【发布时间】:2009-10-12 11:52:10
【问题描述】:
在这个极其简单的示例中,我无法弄清楚这里发生了什么。
问题摘要:我有一个简单的 servlet,如果我手动驱动它,它似乎运行得很好......通过从浏览器发出它的 URL。我所说的“很好”是指:我可以在浏览器 HTML 页面中看到我在 servlet 响应中写的任何内容。
然而,如果我通过 Ajax 代码发出相同的 URL,则 servlet 可以很好地处理请求,甚至“似乎”可以很好地写出响应......但是,我就是这样做的在 Ajax 客户端代码端没有看到任何响应,因此在我的浏览器 HTML 页面中也没有。
进一步,如果我将 XHR 请求同步,浏览器错误控制台会显示以下异常:
错误:未捕获的异常:[Exception...“组件返回失败代码:0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]”nsresult:“0x80004005 (NS_ERROR_FAILURE)”位置:“JS 框架 :: file:/ //home/sd/Desktop/test.html :: callServlet :: line 35" data: no]
环境:
浏览器:Firefox 3.5.3
Servlet 容器:Tomcat 6.0.20
操作系统:Linux / Fedora 11
Ajax 代码:
<!-- test.html -->
<html>
<head>
<script>
var req;
function $(id) {
return document.getElementById(id);
}
function servletCallback() {
var field = $("debugHtmlId");
field.innerHTML += "readyState='" + req.readyState + "'<br> ";
field.innerHTML += "status='" + req.status + "'<br> ";
field.innerHTML += "responseText='" + req.responseText + "' | <br> ";
}
req = new XMLHttpRequest();
req.onreadystatechange = servletCallback;
function callServlet() {
// With async mode off, I get the
// Exception listed above.
// req.open("GET", "http://localhost:8080/aaa/bbb?f=test", false);
req.open("GET", "http://localhost:8080/aaa/bbb?f=test", true);
req.send(null);
}
</script>
</head>
<body>
<input id="callserv" type="submit" value="Call Servlet" onclick="callServlet();" />
<span id="debugHtmlId"></div>
</body>
</html>
Servlet 代码:
// servlet code
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
rsp.setContentType("text/html");
String val = req.getParameter("f");
if(val.equals("test")) {
// Increment value.
++_count;
// Return value.
PrintWriter out = rsp.getWriter();
out.printf("%d\n", _count);
out.close();
// This shows up fine in servlet log.
System.out.printf("%d\n", _count);
}
}
// This variable is incremented and returned on each call to doGet().
private int _count = 0;
}
编辑:
-
包括结果:这是我看到的,例如我的 debugHtmlId 元素的 innerHTML 的值。
就绪状态='1' 就绪状态='1' 就绪状态='2' 状态='0' 响应文本='' | 就绪状态='4' 状态='0' 响应文本='' |
奇怪的行为:还要注意我的 readystatechange 处理程序正在重新进入!我的意思是,我期待在每次状态更改时看到 readyState='...' status='...' responseText='...' 三元组...
【问题讨论】:
标签: ajax servlets xmlhttprequest responsetext