2015-11-04 43 views
-2

我永遠無法理解:是什麼決定的什麼決定是否調用「成功」或「錯誤」功能?

$.ajax({ ..., 
      success : function (retobj) { ... }, 
      error : function (retobj) { ... }, 
      ... 
      }); 

successerror功能是否叫什麼名字?我的控制器可以直接控制哪個被調用?我知道如果我的控制器就一些愚蠢的事,它會叫,但我可以迫使它這樣調用

$.ajax({ ..., 
      url  : 'MyController/CallSuccess', 
      success : function (retobj) { /* this will invetiably be called */}, 
      error : function (retobj) { ... }, 
      ... 
      }); 

public ActionResult CallSuccess (void) 
{ 
    // ... 
} 
+0

該文檔沒有幫助? http://api.jquery.com/jquery.ajax/ – 2015-11-04 18:04:59

+1

如果http調用失敗或者腳本無法解析內容。 – epascarello

+1

這還包括4 **錯誤和5 ** HTTP錯誤。 – gidim

回答

0

你的控制器的操作方法可以控制是否successerrorajax功能通過在您的操作方法中設置Response.StatusCode來調用。

如果Response.StatusCode = (int)HttpStatusCode.OK那麼將調用success函數。

如果Response.StatusCode = (int)HttpStatusCode.InternalServerError那麼將調用error函數。

示例代碼來調用success功能:

$.ajax({ 
     url: 'MyController/CallSuccess', 
     success: function(result) { /* this will be called */ 
     alert('success'); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
     alert('oops, something bad happened'); 
     } 
    }); 

    [HttpGet] 
    public ActionResult CallSuccess() 
    { 
     Response.StatusCode = (int)HttpStatusCode.OK; 
     return Json(new { data = "success" }, JsonRequestBehavior.AllowGet); 
    } 

示例代碼來調用error功能:

$.ajax({ 
     url: 'MyController/CallFailure', 
     success: function(result) { 
     alert('success'); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { /* this will be called */ 
     alert('oops, something bad happened'); 
     } 
    }); 

    [HttpGet] 
    public ActionResult CallFailure() 
    { 
     Response.StatusCode = (int)HttpStatusCode.InternalServerError; 
     return Json(new { data = "error" }, JsonRequestBehavior.AllowGet); 
    } 
相關問題