我正在尝试根据Backbone.js中的国家/地区代码验证电话号码。我需要等到执行ajax回调之后再返回验证结果。我正在使用Jquerys when方法。模型的验证功能是:
validate: function(attrs) {
this.errors = [];
if(attrs['phone'].length>0){
//validate
console.log('before when ');
$.when(this.checkPhoneNumber(attrs)).done(function(response){
console.log('resspone is ');
console.log(response);
if(response.valid!==true){
that.errors.push({input_tag: 'phone', error: 'Please enter a valid phone number'});
}
if(that.errors.length > 0){
return that.errors;
}
});
console.log('after when ');
}
else{
console.log('in the else so no phone number');
if(this.errors.length > 0){
return this.errors;
}
}
},
checkPhoneNumber是:
checkPhoneNumber: function(attrs){
return $.ajax({
url: "http://hidden-oasis-1864.herokuapp.com/check-phone-number/"+attrs['country']+"/"+attrs['phone'],
success: function(response){
console.log('in checkPhoneNumber success');
},
error: function(){
that.errors.push({input_tag: 'phone', error: 'There was an error validating the phone number'});
return that.errors;
}
});
},
在视图中,我这样做:
if (!this.model.isValid()) {
this.processErrors(this.model.validationError);
}
isValid()运行模型的validate()方法。
但是在日志里我总是得到:
before when ContactModel.js:46
after when ContactModel.js:63
MODEL IS VALID ContactItem.js:66
in checkPhoneNumber success
所以当()没有等待。我做错了什么?
答案 0 :(得分:2)
尝试
checkPhoneNumber: function(attrs){
return $.ajax({
url: "http://hidden-oasis-1864.herokuapp.com/check-phone-number/"+attrs['country']+"/"+attrs['phone'],
success: function(response){
console.log('in checkPhoneNumber success');
},
error: function(){
console.log("I FOUND MY PROBLEM");
that.errors.push({input_tag: 'phone', error: 'There was an error validating the phone number'});
return that.errors;
}
});
},
看起来ajax调用返回错误,因此永远不会调用done
。
要注册失败的回调,请使用fail
并注册回调以始终执行使用then
。