【问题标题】:What determines whether the "success" or "error" function is called?是什么决定了调用的是“成功”还是“错误”函数?
【发布时间】:2015-11-04 18:01:19
【问题描述】:

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

【问题讨论】:

  • 文档没有帮助? api.jquery.com/jquery.ajax
  • 如果http调用失败或者脚本无法解析内容。
  • 这还包括 4** 错误和 5** HTTP 错误。
  • 这些使用 HTTP 状态。如果状态为 200,则表示成功。如果是 400 或 500,这些是不同的错误。你想完成什么?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2014-03-14
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2019-07-04
    • 2022-01-22
    • 2010-09-13
    • 1970-01-01
    相关资源
    最近更新 更多