开发者

Stopping unfinished Ajax requests using jQuery

I'm implementing a live search 开发者_运维问答feature on my website(rails). Everytime there is a keypress, I'm submitting the form. But if the user types several characters, several search requests are sent to the server. I was wondering if there is a way to stop the previous(unprocessed) requests. I want only the last request to be successfully processed.

I know there is a abort() method which aborts an ajax request, but I no longer have control over the previous request, so I can't call abort on that. Maybe I'm doing something wrong here.

Anybody?

Thanks

Punit


There is no way to stop an Ajax request using jQuery. A better way of handling this kind of thing is by "debouncing" the event: http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/ (try the first example). That way the event won't fire for every keypress; just when the user pauses for a brief period. Otherwise, you are going to end up with a lot of requests.

There is a way, however:

var lastRequest;
$("input").keypress(function(){
    if (lastRequest){
        lastRequest.abort();
        lastRequest = null;
    }
    lastRequest = $.ajax({type: "POST", url: "some.php", data: "your=data&goes=here"});
});

From: Abort Ajax requests using jQuery

Bootnote: "lastRequest" sounds very villainous.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜