【问题标题】:How can I execute different Jquery ajax callbacks depending on response code?如何根据响应代码执行不同的 Jquery ajax 回调?
【发布时间】:2015-01-06 05:55:34
【问题描述】:

我真正想知道的是执行不同 Jquery ajax 回调的正确方法,具体取决于可能从后端返回的各种响应代码,例如如果 200 那么,如果 401 那么如果其他代码则执行其他操作.

我是 javascript 初学者。

我正在尝试允许用户使用 ajax 将图像保存到后端,如果他们没有注册,它会自动注册并保存图像。

我已经建立了一个不进行自动注册的解决方案。

我认为我已经超出了我的深度,偏离了轨道,迷失在 Ajax Jquery 的承诺和回调中。

这是伪代码:

    users executes save image ajax function
    if response is 200 OK then:
        update page
        finish
    if response is 401 not authorised then:
        execute autoregister ajax function
        try again to save image (not more than 2 retries)
    if some other http error
        alert error to user
        finish

这里是当前函数:

    // after the image is cropped this saves it to the back end
    function saveCroppedImage() {
        $.ajax({type:'post',
            url:'/app/api/images/uploadfrompost/',
            data: { image: _croppedImage, imageid: elementCurrentlyBeingCropped},
            statusCode: {
            401: function() {
                tryCount = 0,
                retryLimit = 3,
                console.log( "401, not authenticated, registering new." );
              if (tryCount <= retryLimit) {
                registerAnon();
                // try again to save image
                tryCount++;
                $.ajax(this);
                }
               }
              }
            })
            .always(function(data) {
                            //refresh all the schedule images with the newly uploaded image
                            });
                        // display previous modal
                        $('#uploadModal').foundation('reveal', 'close');
                    });

    }


function registerAnon() {
    return $.ajax({type:'GET',
        async:   false,
        url:'/app/api/users/registeranon/'
     });
}

【问题讨论】:

  • 您不能执行不同的回调,但回调接收jqXHR 对象作为参数,您可以从中获取响应代码。然后它可以使用ifswitch 来做不同的事情。
  • 顺便说一句,401: 不是对象文字中的有效属性。您需要将其放在引号中:"401":.
  • @Barmar 不正确。它在 JSON 中无效,但对对象文字有效,并且是 jQuery Ajax docs 定义它的方式。

标签: jquery ajax callback promise


【解决方案1】:

试试

var tryCount = 0,
    retryLimit = 3;

function saveCroppedImage() {
    return $.ajax({
        type: "POST",
        url: "/app/api/images/uploadfrompost/",
        data: { image: _croppedImage, imageid: elementCurrentlyBeingCropped },
    })
};

saveCroppedImage()
.always(function (jqxhr, textStatus, errorThrown) {
  // `error`
  if (textStatus !== "success" &&  jqxhr.status === 401) {
    console.log(textStatus, errorThrown, tryCount, retryLimit);
    registerAnon();
    ++tryCount;
    $("#uploadModal").foundation("reveal", "close"); // always do stuff
    // call `savedCroppedImage` if `401` error occurs again ,
    // and `tryCount` less than `retryLimit`
    (function check(tc, rl) {
      if (tc < rl) {
        saveCroppedImage().always(function (jqxhr, textStatus, errorThrown) {
          // `error`
          if (textStatus !== "success" && jqxhr.status === 404) {
            console.log(textStatus, errorThrown, tc, rl);
            ++tc;
            tryCount = tc;
            $("#uploadModal").foundation("reveal", "close"); // always do stuff
            check(tc, rl);
          } 
          // `success`
          else {
            console.log(jqxhr, textStatus, errorThrown)
          }
        }) 
      }
    }(tryCount, retryLimit))
  } 
  // `success` 
  // `jqxhr`:`data`, `errorThrown`:`jqxhr`
  else {
    console.log(jqxhr, textStatus, errorThrown)
  }
});

function registerAnon() {
    return $.ajax({
        type: "GET",
        async: false,
        url: "/app/api/users/registeranon/"
    });
};

jsfiddle http://jsfiddle.net/guest271314/qab212s5/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多