【问题标题】:RedirectToAction not working after successful jquery ajax post? [duplicate]成功的 jquery ajax 发布后 RedirectToAction 不起作用? [复制]
【发布时间】:2013-11-29 10:45:46
【问题描述】:

以下内容不会重定向我的页面:这是 MVC 代码:

    [HttpPost]
    public ActionResult GoHome()
    { 
         return RedirectToAction("Index", "Home");   
    }

这里是 ajax 帖子:

   $.support.cors = true;

            $.ajax({
                type: "POST",
                url: "http://localhost/UserAccount/GoHome",
                dataType: 'json',
                crossDomain: true
            });

发布成功,当它发起 GoHome 操作时,它不会重定向到 Home 控制器的索引操作。

【问题讨论】:

  • $.support.cors = true; 不是必需的。不需要crossDomain: true

标签: c# jquery post asp.net-mvc-2 jquery-post


【解决方案1】:

您不能从 AJAX 帖子重定向。您可以返回要将浏览器重定向到的 URL,然后从 Javascript 重定向。

控制器

[HttpPost]
public ActionResult GoHome()
{ 
     return Json(Url.Action("Index", "Home"));   
}

Javascript

$.ajax({
    type: "POST",
    url: "http://localhost/UserAccount/GoHome",
    dataType: 'json',
    crossDomain: true,
    success: function (data) {
        window.location.href = data;
    }
});

【讨论】:

  • 您好,这主要是为了安全,所以您不能将用户浏览器重定向到可能包含恶意脚本的某些页面?
  • @xaisoft 我认为这更多的是缺乏功能而不是安全决定。
  • @xaisoft 不,这是 HTTP 限制。在正常的 PRG(发布、重定向、获取)期间,服务器接收表单 POST,对其进行处理并返回 HTTP 301/302 重定向到浏览器接收并遵循的另一个页面。 JS/AJAX 不知道如何处理 301/302 重定向,因为它期望 HTTP 200 响应附带有效负载(Json、HTML、文本)。
  • 如果你想让它重定向,你应该使用基本表单发布。
  • @Tommy - 我有一个调用一个操作方法的 ajax 帖子,如果成功,它会创建另一个应该重定向的 ajax 帖子。如何使第二次调用非 ajax?
猜你喜欢
  • 2018-06-02
  • 2014-01-31
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多