如何从Ajax帖子重定向到Servlet到JSP



我正在为我们的系统和index.html进行此脚本,

<script>
    $('#navbar').load('navbar.html');
    $('#errorMessage').hide();
    $("#loginBtn").click(function() { 
         $.post('http://localhost:8080/NewDesignV1/login.action',
            {
                username : $("#username").val(),
                password : $("#password").val()
            }
            ,'html');
    });
</script>

帖子位置是一个servlet,我需要转到此servlet,以便我可以从index.html获取数据,对其进行操作并将其重定向到JSP页面。

我的问题是,我可以从Ajax帖子中获取数据,但是当我使用

时,它不会重定向到JSP页面
request.setAttribute("key", value);
request.getRequestDispatcher("studentprofile.jsp").forward(request, response);

原因是您已经通过$.post调用了它,所以它是ajax方法,实际上request.getRequestDispatcher("studentprofile.jsp").forward(request, response);正在工作,您可以得到它

$("#loginBtn").click(function() { 
     $.post('http://localhost:8080/NewDesignV1/login.action',
        {
            username : $("#username").val(),
            password : $("#password").val()
        },
        function(data){
           console.log(data);//you can get the redirect jsp context
        },
        ,'html');
});

为了让studentprofile.jsp显示,您需要避免使用$.post,可以创建表单然后提交表单:

$("#loginBtn").click(function() { 
    var form = document.createElement("form");
    document.body.appendChild(form);
    $(form).append("<input type='hidden' name='username' value='"+$("#username").val()+"'>");
    $(form).append("<input type='hidden' name='password' value='"+$("#password").val()+"'>");
    form.action="http://localhost:8080/NewDesignV1/login.action";
    form.method="post";
    form.submit();
    $(form).remove();
});

最新更新