如何在$ .ajax回调中RedirectToAction?

Dav*_*Fox 16 ajax asp.net-mvc jquery

我使用$ .ajax()每5秒轮询一次动作方法,如下所示:

$.ajax({
    type: 'GET', url: '/MyController/IsReady/1',
    dataType: 'json', success: function (xhr_data) {
        if (xhr_data.active == 'pending') {
            setTimeout(function () { ajaxRequest(); }, 5000);                  
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

和ActionResult动作:

public ActionResult IsReady(int id)
{
    if(true)
    {
        return RedirectToAction("AnotherAction");
    }
    return Json("pending");
}
Run Code Online (Sandbox Code Playgroud)

我必须将动作返回类型更改为ActionResult才能使用RedirectToAction(最初它是JsonResult并且我正在返回Json(new { active = 'active' };),但它看起来很难重定向并从$ .ajax()成功回调中呈现新视图.我需要从这个轮询ajax回发中重定向到"AnotherAction".Firebug的响应是来自"AnotherAction"的视图,但它不是渲染.

Kir*_*oll 18

您需要使用ajax请求的结果并使用它来运行javascript以手动更新window.location.例如,类似于:

// Your ajax callback:
function(result) {
    if (result.redirectUrl != null) {
        window.location = result.redirectUrl;
    }
}
Run Code Online (Sandbox Code Playgroud)

其中"result"是在完成ajax请求后由jQuery的ajax方法传递给您的参数.(并且要生成URL本身,请使用UrlHelper.GenerateUrl,这是一个基于actions/controllers /等创建URL的MVC助手.)