优化的搜索使用AJAX和关键preSS [英] optimized search using ajax and keypress
问题描述
我有以下code,因为我要搜索一个数据库作为用户输入到一个文本框。下面这张code正常工作,但似乎有点效率低下,因为如果用户输入的真快,我可能会做很多比必要更多的搜索。因此,如果用户键入帆船
我在寻找的帆,赛力,赛林和帆船
我想看看是否有一种方法来检测关键presses之间的任何特定的时间,如果用户停止输入500毫秒或类似这样的东西,所以只能搜索。
有一个最佳实践,这样的事情?
$('#searchString)。键preSS(功能(E){
如果(e.key code == 13){
VAR URL ='/跟踪器/搜索/'+ $(#searchString)VAL()。
$获得(URL,功能(数据){
$('#DIV结果)HTML(数据)。
$('#结果),显示()。
});
}
其他 {
。VAR existingString = $(#searchString)VAL();
如果(existingString.length→2){
VAR URL ='/跟踪器/搜索/'+ existingString;
$获得(URL,功能(数据){
$('#DIV结果)HTML(数据)。
$('#结果),显示()。
});
}
}
您可以做这样的事情:
$('#searchString)。KEYUP(功能(E){
clearTimeout($的数据(这一点,定时器));
如果(e.key code == 13)
搜索(真正的);
其他
$(本)的.data('定时',的setTimeout(搜索,500));
});
功能搜索(力){
。VAR existingString = $(#searchString)VAL();
如果(力和安培;!&安培; existingString.length 3;)的回报; //为不进,不是> 2字符
$获得('/跟踪器/搜索/+ existingString,功能(数据){
$('#DIV结果)HTML(数据)。
$('#结果),显示()。
});
}
这样做是执行搜索(在 KEYUP
,不是键preSS
更好地为这些情况)在 500ms的
通过存储在 #searchString
元素的 的.data()
集合。每个 KEYUP
它清除了定时器,如果密钥输入,立即搜索,如果没有设置一个又一个的 500ms的
自动搜索之前超时。
i have the following code as i want to search a database as a user is typing into a textbox. This code below works fine but it seems a little inefficient as if a user is typing really fast, i am potentially doing many more searches than necessary. So if a user is typing in "sailing"
i am searching on "sail", "saili", "sailin", and "sailing"
i wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.
is there a best practices for something like this?
$('#searchString').keypress(function(e) {
if (e.keyCode == 13) {
var url = '/Tracker/Search/' + $("#searchString").val();
$.get(url, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
else {
var existingString = $("#searchString").val();
if (existingString.length > 2) {
var url = '/Tracker/Search/' + existingString;
$.get(url, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
}
You can do something like this:
$('#searchString').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13)
search(true);
else
$(this).data('timer', setTimeout(search, 500));
});
function search(force) {
var existingString = $("#searchString").val();
if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char
$.get('/Tracker/Search/' + existingString, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
What this does is perform a search (on keyup
, better than keypress
for these situations) after 500ms
by storing a timer on the #searchString
element's .data()
collection. Every keyup
it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500ms
timeout before auto-searching.
这篇关于优化的搜索使用AJAX和关键preSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!