我想对servlet进行ajax调用并打印响应。
我写了index.html
,Assignemnt
servlet和web.xml
,如下所示,但我没有得到警报。出了什么问题?
index.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
<script>
$(document).ready(function() {
$("button").click(function() {
$.get("Assignment", function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form method="GET" action="Assignment" name="showall">
<table>
<tr>
<td><input type="checkbox" name="id1" /></td>
<td>Jim</td>
<td>Knopf</td>
</tr>
<tr>
<td><input type="checkbox" name="id2" /></td>
<td>Jim</td>
<td>Bean</td>
</tr>
</table>
<p>
<button>Send an HTTP GET request to a page and get the
result back</button>
</p>
</form>
</body>
</html>
的Servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.err.println("-------++++");
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
//RequestDispatcher rd = request.getRequestDispatcher("/Assignment");
RequestDispatcher rd = request.getRequestDispatcher("/index.html");
rd.forward(request, response);
}
Servlet映射:
<servlet>
<description>FirstAssignment</description>
<display-name>Assignment</display-name>
<servlet-name>Assignment</servlet-name>
<servlet-class>com.Assignment</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Assignment</servlet-name>
<url-pattern>/Assignment</url-pattern>
</servlet-mapping>
答案 0 :(得分:4)
您根本不需要转发回复。它会覆盖text/plain
响应。删除这些行:
//RequestDispatcher rd = request.getRequestDispatcher("/Assignment");
RequestDispatcher rd = request.getRequestDispatcher("/index.html");
rd.forward(request, response);
无关,w3schools tutorials必须使用huge bag of salt。例如,$("button")
选择器是一个非常糟糕的建议,因为这会影响整个HTML文档中的每个 <button>
元素,而您更愿意将ajax函数绑定到仅由某个ID标识的一个特定按钮。