开发者

Terminating jQuery.ajax() on event (I mean terminating ajax connection to server)

开发者 https://www.devze.com 2023-04-06 04:16 出处:网络
This question should be very familiar for those who have written or tested autocompletion interfaces using JavaScript, (realt开发者_如何学Pythonime ajax stuff).

This question should be very familiar for those who have written or tested autocompletion interfaces using JavaScript, (realt开发者_如何学Pythonime ajax stuff).

I'm coding realtime form validation. The user is typing his username and he can see "OK" or "Taken" massages as he types.

The problem is:

1)I fire $.ajax() on every keyup() or change() event

2)So when the user types fast and the connection is slow there can be a lot of connections open. All of them except the last one are not topical and need to be terminated

3)Moreover, the ping to server can vary, for example from 100ms to 400ms, so not topical answers come last (!!!)

That for sure must be fixed.

What should I do?


http://api.jquery.com/jQuery.ajax/#jqXHR

JQuery Ajax function returns jqXHR Object. You can use .abort() method for terminate previous requests


If it meets your requirements, the easiest way to do this is probably to use the standard JQuery UI Autocomplete plugin. This handles the plumbing for you.

For more complex requirements, you can roll your own. This bindWithDelay plugin is quite handy for deferring the keypress events. As pointed out by @Vlad, when firing the Ajax query be sure to keep a reference to the jqXHR object so you can cancel the request if a second request is made.

if (jqXHR &&  jqXHR.readyState !== 4) {
  jqXHR.abort();
}

jqXHR = $.ajax({
  ...
});

Note that even if the Ajax request is aborted the server will continue to process the request so you will still consume server resources. And of course, in the error handler for your Ajax cal, be sure to ignore the error caused where status === "abort".


While some ajax libraries support aborting requests, I would try to be a little more careful and pre-emptive about flooding the connection.

As I don't think you will see a massive performance improvement from canceling a request,

most likely the server is already sending the packets and they will consume bandwidth either way.

A simple way to prevent spamming requests is put a slight delay on triggering new requests (say 200ms) then if a newer request is triggered before the timeout restart the timer, to some maximum threshold of course.

eg a quota of 1 per second minimum.

This will also prevent the double triggering you will get from catching 2 redundant events.

0

精彩评论

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