如何根据响应代码执行不同的Jquery ajax回调?

时间:2014-11-10 00:47:01

标签: jquery ajax callback promise

我真正想知道的是执行不同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/'
     });
}

1 个答案:

答案 0 :(得分:0)

尝试

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/