我对java很新,我试图在这里发布解决方案:How to use Servlets and Ajax?,但是jQuery调用没有执行servlet。
Servlet代码如下:
package com.morley.app;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
System.out.println("Im working");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
}
我的web.xml映射如下:
<servlet>
<servlet-name>AjaxTest</servlet-name>
<servlet-class>com.test.app.AjaxTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxTest</servlet-name>
<url-pattern>/AjaxTest</url-pattern>
</servlet-mapping>
我的jsp如下:
<head>
<title>SO question 4112686</title>
<script type="text/javascript" src="<%= request.getContextPath() %>/js/jquery-latest.min.js"></script>
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('AjaxTest', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
//alert('ready');
$('#somediv').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
如果有人能帮助我弄清楚为什么doGet没有开火,那将非常感激
答案 0 :(得分:2)
检查是否正在执行ajax命令并将请求发送到正确的地址。
您可以通过执行ctrl + shift + c打开控制台窗口并进入网络来检查它,以帮助您进行调试。 (Firefox为此提供了萤火虫)。
Ps:创建ServLet后重启服务器。 JSP文件启动,但是对于servlet,您需要重新启动服务器才能启动并运行它们。