我知道上述可以通过在 AJAX 调用中使用 quietMillis 来实现,但我使用查询来缓存数据。在这里我无法延迟 AJAX 调用。下面是代码
$('#AssetType').select2({
cacheDataSource: [],
placeholder: ' ',
quietMillis: 3000,
query: function q(query) {
self = this;
var key = query.term;
var cacheData = self.cacheDataSource[key];
if (cacheData) {
query.callback({
results: $.map(cacheData, function (item) {
return {
text: item.LongDescription,
id: item.AssetTypeID
}
})
});
return;
}
else {
$.ajax({
url: 'http://localhost:52377/api/reference/asset/types/' + key,
dataType: 'json',
type: 'GET',
quietMillis: 3000,
//data: function (query) {
// return { assetType: query.term, };
//},
success: function (data) {
self.cacheDataSource[key] = data;
query.callback({
results: $.map(data, function (item) {
return {
text: item.LongDescription,
id: item.AssetTypeID
}
})
});
},
cache: true
})
}
}
});
是否有任何解决方法来延迟 AJAX 调用,以便每次击键都不会触发 AJAX 调用?使用“查询”的原因是为了缓存,仅通过在 AJAX 调用中将缓存设置为 true 是无法实现的。
最佳答案
根据select2 documentation ,您可以轻松做到这一点。
A request is being triggered on every key stroke, can I delay this?
By default, Select2 will trigger a new AJAX request whenever the user changes their search term. You can set a time limit for debouncing requests using the ajax.delay option.
This will tell Select2 to wait 250 milliseconds before sending the request out to your API.
$('select').select2({
ajax: {
url: '/example/api',
delay: 250
}
});
关于javascript - 如何延迟 select-2,以便在用户输入数据后等待一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805457/