Ajax调用servlet并加载新页面

时间:2015-01-17 11:11:32

标签: jquery ajax jsp servlets

我想在点击带有id =" test"的href链接时加载Ajax加载器图像。单击此href后,我想调用一个Jsp Servlet,它将发送一个新的请求来加载一个新的.jsp页面。

此时的问题是servlet将被调用,但他没有对新页面发出请求。有人可以帮帮我吗?

我的代码如下所示:

jsp页面:href link和loader div

<div id="load"></div>
<a href="#" id="test" title="#" class="mainLink">link</a>

的Servlet

public class TestController extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
      // redirect to post
      doPost(request,response);
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
      // send to new jsp page   
      request.setAttribute(getServletContext().getInitParameter("DynamicContentLoader"),"/secure/pages/test/testPage.jsp");
      request.getRequestDispatcher("/collector.jsp").include(request, response);
   }
}

Ajax电话:

<script type="text/javascript">
    $("#test").click(function(e){
        e.preventDefault();
        $.ajax({

        type: "POST",
        url: "secure/TestController.do",  

        beforeSend : function(xhr, opts){
            //show loading gif
            $('#load').addClass('loader');
        },
        success: function(){
           // nothing to do at this time
        },
        complete : function() {
           //remove loading gif
           $('#laden').removeClass('loader');
        }
     });
  });
</script>

这是servlet responseDispatcher将包含一个新的jsp页面的部分:

<c:when test="${not empty requestScope.includeJspContent}">
   <!-- start Dynamic Generated Context -->
   <jsp:include page="${requestScope.includeJspContent}" />
   <!-- end Dynamic Generated Context -->
</c:when>
<c:otherwise>
   <!-- start no dynamic data found -->
   <jsp:include page="/error/no_dynamic_content.jsp" />
   <!-- end no dynamic data found -->
</c:otherwise>

1 个答案:

答案 0 :(得分:0)

自从我使用JavaEE以来已经过了太多年,但据我记得,渲染jsp的标准方法是使用RequestDispatcher.forward()方法,如果不连接输出。也许这也是问题所在。

但我可以肯定的是,您不会将您的回复包括在您的网页中。将其添加到您的success处理程序:

success: function(resp){
    $('#load').removeClass('loader');
    $('#load').html(resp);
},
相关问题