我正在构建一个 jQuery AutoSuggest 插件,灵感来自 Apple 的聚光灯。
这是通用代码:
$(document).ready(function() {
$('#q').bind('keyup', function() {
if( $(this).val().length == 0) {
// Hide the q-suggestions box
$('#q-suggestions').fadeOut();
} else {
// Show the AJAX Spinner
$("#q").css("background-image","url(/images/ajax-loader.gif)");
$.ajax({
url: '/search/spotlight/',
data: {"q": $(this).val()},
success: function(data) {
$('#q-suggestions').fadeIn(); // Show the q-suggestions box
$('#q-suggestions').html(data); // Fill the q-suggestions box
// Hide the AJAX Spinner
$("#q").css("background-image","url(/images/icon-search.gif)");
}
});
}
});
我想优雅地解决的问题不是杀死服务器。现在,上面的代码在您每次键入键时都会访问服务器,并且不会等待您基本上完成键入。解决这个问题的最佳方法是什么?A. 终止以前的 AJAX 请求?B. 某种类型的 AJAX 缓存?C. 添加某种延迟以仅在该人停止输入 300 毫秒左右时才提交 .AJAX()?