0

我想对 servlet 进行 ajax 调用并打印响应。我已经编写了index.html, Assignemntservlet 和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>

小服务程序:

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>
4

1 回答 1

4

您根本不需要转发响应。它会覆盖text/plain响应。删除这些行:

//RequestDispatcher rd = request.getRequestDispatcher("/Assignment");
RequestDispatcher rd = request.getRequestDispatcher("/index.html");
rd.forward(request, response);

也可以看看:


与具体问题无关, w3schools 教程必须带着一大袋盐。例如,$("button")选择器是一个非常糟糕的建议,因为这会影响整个 HTML 文档中的每个 <button>元素,而您宁愿将 ajax 函数绑定到仅由某个 ID 标识的特定按钮。

于 2012-12-28T16:53:41.700 回答