开发者

Slow/lagging/stopping search mechanism using AJAX in a textbox everytime a keypress

开发者 https://www.devze.com 2023-03-18 18:36 出处:网络
I created a webbapp using ASP.NET, C# and jQuery. The webapp will search a record in a database. Like for example in the main page, I will type a name of the record and it will automatically show all

I created a webbapp using ASP.NET, C# and jQuery. The webapp will search a record in a database. Like for example in the main page, I will type a name of the record and it will automatically show all record with the same name. So basically, everytime I type a character in the textbox search it will automatically trigger an javascript function and will trigger a request to fetch the data.

<input size="40" id="searchTxt"  name="searchTxt" type="text"/>

and below is the jQuery and javascript function

$('searchTxt').bind('keyup', function() {
    var txt = $('#searchTxt').val();
    xmlhttp.open("POST","/Search/?srch="+txt,false);    
    xmlhttp.send();
    document.getElementById("Show").innerHTML=xmlhttp.responseText;
});

Is it possible to separate开发者_如何学Python the searching in another thread or another process so that the typing in the search box is smooth and not lagging or stopping.

Please advise.

Many thanks.


You need to make an asynchronous AJAX request, by calling $.ajax.


  1. Make sure that your xmlhttp is set to asynchronous so that the document won't freeze.
  2. Cancel the preceding requests every keypress since you want the latest value of your search box to be searched instead of the previous values.

Try this:

function search()
{
 try
 {
    xhr.abort();
    xhr = null;
 }
 catch(e)
 {
 }
 xhr = 
 $.ajax({
     type: "POST",
     url: "search.php",
     data: "keyword=" + $('#SearchBox').val(),
     success: function(Data)
     {
        /* Write result to ResultBox (div or something) */
        $('#ResultBox').html(Data);
     }
 });
}
0

精彩评论

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