【问题标题】:Why the response.sendRedirect() in servlet doesn't work after receiving the post request of JQuery?为什么servlet中的response.sendRedirect()在收到JQuery的post请求后不起作用?
【发布时间】:2012-05-29 13:38:49
【问题描述】:

在 blog-edit.html 中,使用 JQuery 将 post 请求发送到服务器端(java servlet)。

$("#btn").click(function() {
                    $.post("/blog/handler",{"content":$('#textarea').val()},
                    function(data){
                        alert("Data Loaded: " + data);
                        if(data.toString().length>1){
                            alert("Saved!")
                        }else{
                            alert("Failed!")
                        }
                    })

在服务器端:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String content = request.getParameter("content");
            System.out.println(content);

            response.sendRedirect("/blog/list");
            return;
    }

我看到的是服务器端正在打印来自 html 的内容,并且弹出警报窗口说“已保存!”。但是重定向功能不起作用

搜索后我别无选择,只能使用jquery重定向:

if(data.toString().length>1){
                            alert("Saved!")
                            window.location.replace("/blog/list")
                        }

它有效,但这不是我想要的

请帮忙

【问题讨论】:

  • servlet 被调用了吗?你看到你的 System.out.println(content) 了吗?
  • 是的,我可以在 servlet 中看到输出

标签: java jquery html servlets redirect


【解决方案1】:

在使用 ajax 时。你不能执行服务器端重定向。

但是,在这种情况下,有更好的方法可以在客户端上重定向。

See Here

【讨论】:

  • 使用 ajax 时。您不能执行服务器端重定向。为什么?!
  • 就是这样。你需要自己阅读一些关于它的东西。在使用 ajax 之前。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多