我认为您的方法会淹没服务器,因为您在每次击键时都会向服务器发送请求。即使您像@SravanS 所说的那样在客户端中止请求,服务器仍将接收并开始处理所有请求。一旦发送的 HTTP 请求已经在网络上,你不能停止它,你可以做的是没有客户端中止它,我假设通知服务器或只是忽略它发送的响应,但你仍然在泛滥它。
也许实现延迟以识别用户何时停止输入将是最好的方法。这是一个通用的延迟事件处理程序工厂,非常易于使用,只需将您的函数传递给它并为其分配延迟。如果两次击键之间经过 X 毫秒,则会发送一个请求,但如果在该延迟之前发生另一个击键,您甚至不会发出请求。
function delayedEvent(eventHandler, delay) {
var lastTimeout = null;
return function () {
var that = this,
args= Array.prototype.slice.call(arguments).sort();
if (lastTimeout !== null)
window.clearTimeout(lastTimeout);
lastTimeout = window.setTimeout(function () {
eventHandler.apply(that, args);
}, delay);
};
}
$('... selector ...').on('event', delayedEvent(function () { ... your code ... }, 500));
编辑:这是实现队列的方式,我没有测试过这段代码,将其用作起点。
function eventQueue(requestMaker) {
// Here we store the last event queued, it'll wait until all the already running events are done.
var lastQueued = null,
runningQueue = [];
// Push a new event into the running queue
function pushRunning(toPush) {
runningQueue.push(toPush.done(
// It is necesary to use an IIFE to get the index by value and not by reference
(function (index) {
return function() {
// Remove this event from the runningqueue
runningQueue.splice(index, 1);
// If the queue has been completed, start running the last event sent
if (lastQueued !== null && runningQueue.length === 0) {
pushRunning(lastQueued());
}
}
}(runningQueue.lenght));
));
}
return function () {
var that = this,
args = Array.prototype.slice.call(arguments).sort();
// Some events are already running, just override the lastQueued
if (runningQueue.length > 0) {
lastQueued = requestMaker.bind(that, args);
} else {
// Nothing queued run this event straight away, and queue it as running
pushRunning(requestMaker.apply(that, args));
}
};
}
$('... selector ...').on('event', eventQueue(function () {
// It's extremely important that you return the jquery $.ajax Promise
return $.ajax(...);
}, 500));