【发布时间】:2019-01-12 03:35:45
【问题描述】:
我正在将我在 wordpress 上的 cmets 变成一个 ajax 驱动的系统。
到目前为止一切都很好,直到我遇到了 .catch() 方法在 .then() 方法之后直接触发的问题。
这是我的代码...
Ajax 引擎
commentAPI: function(action, encoded, userID) {
let self = this;
return new Promise(function (resolve, reject) {
//console.log("ajax call to " + self.ajaxURL + " with action " + action);
jQuery.ajax({
url: self.ajaxURL,
type: 'post',
data: 'action='+action+'&data='+encoded,
dataType: 'json',
success: function(data, code, jqXHR) { resolve(data); },
fail: function(jqXHR, status, err) { console.log('ajax error = ' + err ); reject(err); },
beforeSend: function() {} //display loading gif
});
});
},
处理评论表单提交的方法
handleReplyFormSubmit: function(form) {
let self = this;
this.removeErrorHtml(form);
// Serialize form to name=value string
const formdata = jQuery(form).serialize();
// Validate inputs
// * Wordpress doing this for now and providing error resonse
// Encoode data for easy sending
const encodedJSON = btoa( formdata );
this.commentAPI('dt_submitAjaxComment', encodedJSON).then(function(response){
console.log('firing then');
if( response.error == true ) {
self.printFormError(form, response.errorMsg);
}
else {
let html = response.commentHTML;
console.log('html returned' + html)
jQuery(form).append(html);
Jquery(form).remove();
}
}).catch(function(err) {
console.log('firing catch');
if( err !== undefined && err.length > 0 ) {
self.printFormError(form, err);
}
else {
self.printFormError(form, 'Unkown error');
}
});
return false;
},
代码正在做它应该做的事情,但是 catch 方法也被触发了,这使得错误处理令人沮丧......
注意它是如何被触发的
console.log('firing catch')
但这不是(在 ajax 失败函数中)
console.log('ajax error = ' + err );
我做错了吗?
【问题讨论】:
标签: javascript ajax