Asp.net-Mvc
如何在 $.ajax 回調中 RedirectToAction?
我使用 $.ajax() 每 5 秒輪詢一次操作方法,如下所示:
$.ajax({ type: 'GET', url: '/MyController/IsReady/1', dataType: 'json', success: function (xhr_data) { if (xhr_data.active == 'pending') { setTimeout(function () { ajaxRequest(); }, 5000); } } });和 ActionResult 動作:
public ActionResult IsReady(int id) { if(true) { return RedirectToAction("AnotherAction"); } return Json("pending"); }我必須將操作返回類型更改為 ActionResult 才能使用 RedirectToAction (最初它是 JsonResult 並且我正在返回
Json(new { active = 'active' };),但它看起來很難從 $.ajax() 成功回調中重定向和呈現新視圖。我需要從這個輪詢 ajax 回發中重定向到“AnotherAction”。Firebug 的響應是來自“AnotherAction”的視圖,但它沒有呈現。
您需要使用 ajax 請求的結果並使用它來執行 javascript 以自己手動更新 window.location 。例如,類似:
// Your ajax callback: function(result) { if (result.redirectUrl != null) { window.location = result.redirectUrl; } }其中“結果”是 ajax 請求完成後 jQuery 的 ajax 方法傳遞給您的參數。(要生成 URL 本身,請使用
UrlHelper.GenerateUrl,它是一個 MVC 幫助程序,可根據操作/控制器/等創建 URL。)