2010-08-20 41 views
12

我使用$阿賈克斯()以查詢操作方法每隔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」的視圖,但它不是渲染。

回答

15

您需要使用您的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)

+0

發現了另一篇文章中類似的東西經過詳盡的搜索。唯一不同的是它使用了window.location.replace。謝謝! – 2010-08-20 22:24:51

2

我知道這是一個超級老的文章,但淘寶網後,這仍然是在谷歌最佳答案,我最終使用不同的解決方案。如果你想使用純RedirectToAction,這也可以。 RedirectToAction響應包含視圖的完整標記。

C#:

return RedirectToAction("Action", "Controller", new { myRouteValue = foo}); 

JS:

$.ajax({ 
    type: "POST", 
    url: "./PostController/PostAction", 
    data: data, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    complete: function (result) { 
     if (result.responseText) { 
      $('body').html(result.responseText); 
     } 
    } 
}); 
0

C#運作良好

我只是改變了JS,因爲responseText的不是爲我工作:

$.ajax({ 
     type: "POST", 
     url: posturl, 
     contentType: false, 
     processData: false, 
     async: false, 
     data: requestjson, 
     success: function(result) { 
      if (result) { 
       $('body').html(result); 
      } 
     }, 

     error: function (xhr, status, p3, p4){ 
      var err = "Error " + " " + status + " " + p3 + " " + p4; 
      if (xhr.responseText && xhr.responseText[0] == "{") 
       err = JSON.parse(xhr.responseText).Message; 
      console.log(err); 
     } 
    }); 
0

您可以使用Html.RenderAction幫手視圖:

public ActionResult IsReady(int id) 
{ 
    if(true) 
    { 
     ViewBag.Action = "AnotherAction"; 
     return PartialView("_AjaxRedirect"); 
    } 
    return Json("pending"); 
} 

並在 「_AjaxRedirect」 局部視圖:

@{ 
    string action = ViewBag.ActionName; 
    Html.RenderAction(action); 
} 

參考: https://stackoverflow.com/a/49137153/150342