我怎样才能在$阿贾克斯回调RedirectToAction? [英] How can I RedirectToAction within $.ajax callback?

查看:145
本文介绍了我怎样才能在$阿贾克斯回调RedirectToAction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用$阿贾克斯()轮询操作方法每5秒如下:

I use $.ajax() to poll an action method every 5 seconds as follows:

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

和ActionResult的行动:

and the ActionResult action:

public ActionResult IsReady(int id)
{
    if(true)
    {
        return RedirectToAction("AnotherAction");
    }
    return Json("pending");
}

我不得不改变操作返回类型,才能使用RedirectToAction来的ActionResult(最初是JsonResult,我是回 JSON(新{积极='主动'}; ),但它看起来有些麻烦重定向并从$。阿贾克斯()成功回调中呈现了新的视角。我需要从这个投票阿贾克斯回发中重定向到AnotherAction。Firebug的反应是AnotherAction视图,但它不是渲染。

I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.

推荐答案

您需要消耗你的Ajax请求的结果,并用它来运行JavaScript手动window.location的自行更新。例如,是这样的:

You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:

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

在哪里结果是Ajax请求完成后传递给你的jQuery的Ajax方法的参数。 (并生成URL本身,使用 UrlHelper.GenerateUrl ,这是一个MVC的帮助创建基于关闭的网址动作/控制器的/ etc。)

Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)

这篇关于我怎样才能在$阿贾克斯回调RedirectToAction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆