我正在尝试在用户完成打字后获得产品。但是,当用户完成键入操作后,方法将多次运行一次。
如果用户键入“ apple” fetchProducts
方法将运行五次并发送5个ajax请求。我如何一次减少费用(除非您用户开始搜索其他产品)
$(document).on("keyup keydown", 'input.select2-search__field', function (e) {
let timer,
interval = 2000,
searchText = this.value;
if (e.type == "keyup") {
clearTimeout(timer);
timer = setTimeout(fetchProducts, interval);
}
if (e.type == "keydown") {
clearTimeout(timer);
}
function fetchProducts() {
$.ajax({
url: "../../../products/get-by-select-search",
type: "post",
dataType: "json",
headers: {
"X-CSRF-TOKEN": $("meta[name=csrf-token]").attr("content")
},
data: {search: searchText},
success: function (response) {
product.find('option').remove();
product.select2({
theme: "classic",
data: response
})
.val(null)
.trigger("change");
}
});
}
});