我正在使用select2填充代码中的下拉菜单之一。最近,有人要求我捕获服务器500错误,并在对服务器的此类Ajax失败调用中向最终用户显示更好的错误消息。我使用了一种建议的使用传输方法的方式来插入对ajax对象的成功调用和失败调用,如下所示。
var _that = this;
return {
multiple: true,
ajax: {
quietMillis: 100,
url: '<url>', // available test sections are the same for nodes and enemy test sections
type: 'POST',
data: dataObject,
results: (data: any, page: number, context: any) => {
return {
results: data,
context: context
};
},
/* using transport to hook fail method for any server errors like 500. */
transport: function (params: any, success: any, failure: any) {
//chaining the success and fail calls.
return $.ajax(params)
.then(success)
/* pass on the failed select2 object so that callback method ensure to close the dropdown */
.fail(_that.select2LoadingFailed.bind($.extend(_that, { failedSelect2: this})));
},
}
当然,这是select2对象的必要部分,而不是完整的代码,但我想足以解释我如何使用select2。
现在在出现前500个错误时,实际上已将调用传递给that.select2LoadingFailed方法,但是在连续调用中,我在select2 js上遇到了以下错误
Uncaught TypeError: handler.abort is not a function
at select2.js:379
这是select2中的罪魁祸首代码
function ajax(options) {
var timeout, // current scheduled but not yet executed request
requestSequence = 0, // sequence used to drop out-of-order responses
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
requestSequence += 1; // increment the sequence
var requestNumber = requestSequence, // this request's sequence number
data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.ajax,
type = options.type || 'GET', // set type of request (GET or POST)
params = {};
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
//this guy is throwing error on .abort method call
if( null !== handler) { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
有什么建议我在这里做错了吗?