【发布时间】: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对象作为参数,您可以从中获取响应代码。然后它可以使用if或switch来做不同的事情。 -
顺便说一句,
401:不是对象文字中的有效属性。您需要将其放在引号中:"401":. -
@Barmar 不正确。它在 JSON 中无效,但对对象文字有效,并且是 jQuery Ajax docs 定义它的方式。
标签: jquery ajax callback promise