如何防止AJAX请求(在keydown上调用)在自动提交搜索框中阻止进一步的击键(在PHP中)?

I've made a searchbox in PHP, wherein as the user types in the search string, an autosuggestion div appears and shows search results.I have been successful in achieving the end result, but there is an issue:

Since I'm calling the AJAX on every keystroke, I am not able to type anything in running, since every keydown first waits the ajax request to get completed, hence blocking any further keydown. So I first type a character,have to wait for search results and then type another character. No one wants to wait this long.

I can think of an alternative in which I have to prefetch all the possible search result, like in this example:

http://jqueryui.com/autocomplete/

But this won't be a good solution in my case as I want to load search result from the server at the time of keypress only.(Of course that's how even Google search works).

Is there any way I can make the keystrokes independent of AJAX and still let AJAX do it's own thing without blocking my keyboard input?

If you don't want you're user being forced to wait for the return of the ajax call after each keystrokes before being able to type another letter, you'll need to abort the ajax call onkeydown.

One way of doing so is to check if the ajax request isRunning if it is abort it and run a new one with the new query.

if(xhrRunning)
    xhr.abort(); //kill the request

xhrRunning = true;
xhr = $.ajax({
    type: "POST",
    url: "suggestion.php",
    data: "q="+var,
    success: function(msg){
       xhrRunning = false;
       //Do you're treatement
    }
});

PS : Make sure that in you're code async is not set to false if set to false synchronous requests may temporarily lock the browser, disabling any actions while the request is active.