为什么servlet发布响应后,innerHTML不起作用?

时间:2019-02-10 13:20:49

标签: javascript jsp servlets httpresponse

我希望在jsp页面中捕获来自servlet的响应。我为此使用javascript。这是代码:

TestServlet.java:

    package com.test;

    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        String testString = "Load Check";
        //request.setAttribute("test", testString);
        //request.getRequestDispatcher("").include(request, response);
        response.getWriter().write("Test Success");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Test.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Test JSP</title>
    </head>
    <body>
    <script type="text/javascript">
      function callServeltAndGetResponse(){
    var servlet = new XMLHttpRequest();
    servlet.onreadystatechange = function(){
        var servletResponse = servlet.responseText;
        document.getElementById("response").innerHTML = servletResponse;
    }
    servlet.open('GET','TestServlet',true);
}

    </script>
    <form onSubmit="javascript:callServletAndGetResponse()">
    <input type=submit>
    </form>
    <div id="response"></div>
    </body>
    </html> 

在上述jsp页面中,尽管servlet编写了响应,但javascript并未更改divcontent。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要阻止默认的表单提交过程,否则页面将重新加载

尝试:

<form onSubmit="javascript:callServletAndGetResponse(); return false">