是什么决定了"成功"或"错误"函数被称为?

时间:2015-11-04 18:01:20

标签: javascript jquery asp.net asp.net-mvc

我永远不明白:是什么决定了successerror的功能

$.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 )
 {
    // ...
 }

1 个答案:

答案 0 :(得分:0)

您的控制器操作方法可以控制是否通过在操作方法中设置success来调用errorajax 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);
    }