为什么servlet正在发布回复后的innerHTML不起作用?

问题描述 投票:0回答:1

我想从servlet响应在JSP页面被捕获。我使用JavaScript这一点。下面是代码:

test Servlet.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页面中,divcontent不是由JavaScript虽然写的servlet的响应变化。我究竟做错了什么?

javascript jsp servlets httpresponse
1个回答
0
投票

你需要阻止默认表单提交过程或页面将重新加载

尝试:

<form onSubmit="javascript:callServletAndGetResponse(); return false">
© www.soinside.com 2019 - 2024. All rights reserved.