RequestDispatcher的Ajax无法正常工作

时间:2013-11-15 18:16:51

标签: ajax jsp servlets

我在JSP中创建了一个表单first.jsp

    <input type="radio" name="actionType" value="edit_notice" class="noticeaction">Edit 
    <input type="radio" name="actionType" value="delete_notice" class="noticeaction">Delete 
    <input type="radio" name="actionType" value="post_notice" class="noticeaction">Post Notice 
    <br/><br/><br/>

    <input type="submit" name="reviewNoticeSubmit" value="Submit" id="reviewNoticeSubmit">

ajax调用的jQuery是:

else if(actionToPerform == "edit_notice")
            {
                var noticeId = $(".selectednotice").val();
                var param = "noticeId=" + noticeId;

                jQuery.ajax({
                    type:"POST",
                    url : "reviewnoticeaction/editnotice",
                    data : param,
                    beforeSend : function() {

                    },
                    complete : function() {

                    },
                    success : function(data) {

                    },
                    error : function(xmlHttpRequest, textStatus, errorThrown) {
                        alert("Error occured. Unable to open editor");
                    }

                });

            }

以下是从数据库中获取一些值并分配给属性的servlet代码,我正在尝试将其转发到另一个jsp页面。它不起作用。

request.setAttribute("firstData", editNoticeRs.getString("firstData"));
                    request.setAttribute("secondData", editNoticeRs.getDate("secondData"));
                    request.setAttribute("thirdData", editNoticeRs.getDate("thirdData"));

RequestDispatcher rd = request.getRequestDispatcher("second.jsp");
    rd.forward(request, response);

PS:如果我无法将其转发到另一个jsp,是否可以在同一个jsp页面中获取值并访问该值?如果是的话怎么样?

2 个答案:

答案 0 :(得分:0)

您无需从servlet为Ajax分派到JSP。只需在servlet中执行所有操作就会更简单。是的,在Ajax中,您可以读取servlet的输出。这就是成功函数中的“数据”变量。

 success : function(data) {
   alert(data);
 },

当然,如果需要,您仍然可以从servlet调度到JSP。可能它似乎不起作用的原因是你对返回的输出没有任何作用。

答案 1 :(得分:0)

如果要从servlet简单调用

将JSON或String数据返回给ajax成功处理程序
PrintWriter out=response.getWriter();
out.println("String Data to return");

或者如果是json

PrintWriter out=response.getWriter();
StringBuilder data = new StringBuilder()
data.append("{");
data.append("'name':");
data.append("'arock',");
data.append("'Language':");
data.append("'Java'");
data.append("}");
out.println(data.toString());