是什么决定了“;成功;或“;错误“;函数被调用

What determines whether the "success" or "error" function is called?

本文关键字:函数 调用 错误 成功 决定了 是什么      更新时间:2023-09-26

我一直不明白:是什么决定了的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 )
 {
    // ...
 }

您的控制器操作方法可以通过在操作方法中设置Response.StatusCode来控制是调用success还是error ajax函数。

如果是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);
    }