【问题标题】:How to handle ajax 201如何处理ajax 201
【发布时间】:2019-05-09 22:39:09
【问题描述】:

当进行 ajax 调用时,请参阅下面的示例 success 确实会重新调整 201 状态。您如何更好地处理这些成功函数中的 200、201?

$.ajax({
    type: "POST",
    dataType: "json",
    url: "http://api.domain.com/sms",
    data: {
      // Send value in mobile input field.
      mobile: $("#mobile").val(),
    },
    // On successful AJAX call do the following.
    success: function(data) {
      $('#messageText').text('SMS successfully sent');
    },
    error: function(jqXhr) {
      data = JSON.parse(jqXhr.responseText);
    }
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    使用statusCode 对象:

    var handle200 = function(data, textStatus, jqXHR) {
        alert('200'); // success codes have the success signature
    };
    
    var handle201 = function(data, textStatus, jqXHR) {
        alert('201'); // success codes have the success signature
        // test it if you are in doubt:
        console.log(data);
        console.log(textStatus);
        console.log(jqXHR);
    };
    
    var handle404 = function(jqXHR, textStatus, errorThrown) {
        alert('404'); // failing codes have the error signature
    });
    
    var request = $.ajax({
        type: 'POST',
        url: '/myresource/posttarget',
        data: { name: 'john' },
        statusCode: {
            200: handle200,
            201: handle201,
            404: handle404
        }
    });
    

    【讨论】:

    【解决方案2】:

    这是一个老问题,但我还是想发表评论。

    我遇到了同样的问题,为我解决的一件事是未设置“dataType”。当您执行此操作时,jQuery 将尝试猜测服务器返回的数据类型,并且当您的服务器返回没​​有内容的 201 时不会抛出错误。

    希望对你有帮助。

    【讨论】:

    • 感谢它的帮助。我发送了 JSON 内容,因为我可以管理服务器。
    【解决方案3】:

    我们遇到了类似的问题;查看 jquery 1.9 源代码,201 状态代码需要内容。如果 201 没有返回内容(或内容类型错误),则调用失败回调。

    【讨论】:

      【解决方案4】:

      Data inserted successful but jquery still returning error

      这里的答案似乎是您现在可以使用的解决方法。但是,如果您使用跨域,AJAX 会出现一些问题。看看这个 SOF 线程:

      Problems Reading the HTTP Status/Error Code from jQuery AJAX

      【讨论】:

        【解决方案5】:

        代替

        ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
        

        我用过

        ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
        

        如果成功,detailVO 是我的目标。然后在浏览器中我得到了成功功能的响应。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-28
          • 2016-05-13
          • 2011-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-27
          相关资源
          最近更新 更多