How to make a ajax filter in jquery?
I am trying to make a filtering where a user would search by last name. Right now I have it on keypress but of course this does too many ajax requests so I would rather have it after a few keys or something like that.
I am return all the results as a table(I have a partial view that generates a table with the info in it)
$(function ()
{
$('#LastName').keypress(function ()
{
$.post('ActionMethod', { 'lastName': $(this).val() }, function (response)
{
$('#results').html(response);
});
});
});
开发者_运维百科
Any ideas how I should do this. I guess the logic would be similar to a auto complete and I know they can set like how many keystrokes before you query db.
I think you should just use timeouts and delay the execution of the ajax call. If a keypress occurs before the execution then reset the timer...
$(function ()
{
var timer;
$('#LastName').keypress(function ()
{
var _this = this; // we need to store the this to a variable since it will be called out of context from the timeout
clearTimeout(timer);
timer = setTimeout(function(){
$.post('ActionMethod', { 'lastName': $(_this).val() }, function (response)
{
$('#results').html(response);
});
}, 500); // delay for 500 milliseconds
});
});
How about something like...
$(function ()
{
$('#LastName').keypress(function ()
{
if($(this).val().length > 4)
{
$.post('ActionMethod', { 'lastName': $(this).val() }, function (response)
{
$('#results').html(response);
});
}
});
});
You could pre-load all unique values for names beforehand, and work with that array. This works alright if you don't have too many values. For your case, I guess, I doubt there will be thousands or millions of unique last names...
You could also set a time limit between ajax requests, rather than the number of keystrokes. (Like Gaby suggested).
The jQuery throttle debounce plugin provides an easy way to handle rate-limiting.
精彩评论