将Servlet变量传递给Javascript

时间:2014-03-26 11:01:48

标签: javascript ajax jsp servlets

我有一个JSP页面,用于向HTTPServelet提交一些数据。我需要在servlet中成功完成任务后显示警告,因此我有一个JavaScript AJAX函数,它在JSP Page的onSubmit事件中执行。但是当我点击提交按钮时,AJAX功能不会随之执行。

这是我的Javascript函数:

function alerts(servlet) {

    var xhr = new XMLHttpRequest();

    xhr.open("POST", servlet, true);
    console.log("connected to "+servlet);
    xhr.send(null);
    xhr.onreadystatechange = function() { //this function does not execute
        if (xhr.readyState === 4) {

            if (xhr.status === 200) {

                content = xhr.responseText;
                var objects = JSON.parse(content);
                console.log(objects);

                var elemant = document.getElementById("tblObjects");
                var child = elemant.children;
                var childLength = child.length;
                if (0 < child.length) {
                    for (i = 0; i < childLength; i++) {
                        deleteElamant("tblObj");
                    }
                }

            }
        }
    };
}

我的Servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try {
            //Do somethings inside Servlet

            response.getWriter().write("my alert messege to JavaScript");
            RequestDispatcher rd = request.getRequestDispatcher("/NextServlet");
            rd.forward(request, response);
        } catch (Exception ex) {
        } 
    }

0 个答案:

没有答案