繁体   English   中英

从Jquery调用action方法并将用户重定向到外部站点

[英]calling action method from Jquery and redirecting the user to an external site

我想从jQuery调用mvc控制器的action方法,并且当该action方法被调用时,用户应该被转移到另一个站点。 我尝试使用jquery ajax来执行此操作,但是在response.redirect之后,我的页面仍停留在相同的URL上,没有任何更改。

 $.ajax({
        url: '/Controller/Action',
        success: function (Data) {
        //don't want to use this callback as I require only calling the 
        action method
        }
    });

并在控制器中

public void Action(){
  // process the request and redirect
    Response.Redirect("url", false);
 }

谁能帮助我了解上述代码中的问题所在。

提前致谢。

您可以尝试这样的事情

return Redirect("http://www.google.com");

或尝试使用javascript

public ActionResult Index()
{
 return Content("<script>window.location = 'http://www.example.com';
 </script>");
}

您可以检查此链接以了解有关Redirect与RedirectResult的信息

返回新的RedirectResult()与返回Redirect()

我尝试了,它正在工作。 我希望这有帮助 :-)

的HTML

 <button class="btn btn-primary" onclick="RedirectTosite()">Redirect To Google</button>

jQuery调用

function RedirectTosite() {
    $.ajax({
        url: '/Employee/RedirectTosite',
        success: function (Data)
        {
            window.location = Data;              
        }
    });
}

控制者

 public JsonResult RedirectTosite()
    {
        return Json("http://www.google.com", JsonRequestBehavior.AllowGet);
    }

我不知道为什么如果您不打算对数据库进行任何数据操作,而只是为了重定向到页面,而只是使用诸如

window.location.href = '/Controller/Action/'

好的,我确信您已经对void方法进行了一些工作,如果您在void方法上重定向页面,那么ajax请求将失败,并且您不会被重定向到另一个页面。 为此,您只需删除代码行

    Response.Redirect("url", false);

从控制器并在ajax的成功函数中编写如下代码。

window.location.href = '/Controller/Action/'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM