What I'm currently doing is using jQuery to perform an ajax request on every keypress. So if my user typed d-o-n-k-e-y, it would send one request for each letter. However, since they take different paths to the server on the network, if they type d-o-n-k-e-y too fast, they don't always arrive in order. They might arrive as D-n-o-k-y-e, and react accordingly. Is there a good way to make sure all the re开发者_开发百科quests get sent in order?
I don't think waiting for confirmation from a request before sending the next one would work, because it would slow the information transfer so much. Does anyone have any ideas?
Thanks.
From: http://api.jquery.com/jQuery.ajax/
async boolean
Default: true
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Also, it may not be the best idea to send an ajax request every single keystroke. Can't you use a timeout and send a don
and key
request (buffered up to every 300 ms for example)?
Here are some ideas-
Cancel your old requests as new ones are made. This will minimally reduce load to the server and achieve what you ask.
Instead of making your server keep track of which requests came when, it would only take a small helper object to keep track of which is the latest request. var mostRecentRequest = XHR({ success: function() { if( this === mostRecentRequest ) { ... } } });
As mentioned above, only make a call to the server when the user stops typing for a moment. Do a setTimeout() on keyup that fires ~500ms later and sends the request, and cancel and reset that timeout each time a new key is pressed.
Do NOT do synchronous XHR requests in the browser. Ever. Under any circumstance. The entire browser will hang until the request is completed, which could be as much as a couple of seconds.
精彩评论