我永远不明白:是什么决定了success
或error
的功能
$.ajax( { ...,
success : function ( retobj ) { ... },
error : function ( retobj ) { ... },
...
} );
被称为?我的控制器可以直接控制哪个叫做?我知道如果我的控制器做了一些愚蠢的事情就会被调用,但是我可以强制它被称为
$.ajax( { ...,
url : 'MyController/CallSuccess',
success : function ( retobj ) { /* this will invetiably be called */},
error : function ( retobj ) { ... },
...
} );
public ActionResult CallSuccess ( void )
{
// ...
}
答案 0 :(得分:0)
您的控制器操作方法可以控制是否通过在操作方法中设置success
来调用error
或ajax
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);
}