是keyup上的搜索太低效了

Is search onkeyup too unefficient?

本文关键字:搜索 keyup      更新时间:2023-09-26

我有这样一个表单,管理员在其中搜索玩家列表,我做到了,所以当他搜索时,在keyup上运行一个php脚本,搜索他键入的%string%。类似谷歌的东西。

如果管理员快速键入一个名称,我想知道这是否不好。或者如果它可以被滥用到";洪水;服务器。我在一个共享服务器上,最多可以运行15个进程。

如果是这样,解决这个问题的最佳方法是什么?我想在搜索之间增加一个1秒的限制。还有其他想法吗?

function getusers()
{
    var whou = ($("#who").val());
    
    $("#theadmins").load("searchusers.php", {who : whou});
}
<input id='"who'" onkeyup='"getusers()'" class='"'" type='"text'"  placeholder='"username'" width='"100'" maxlength='"32'" size='"32'" />

编辑::已经很久了,但有些人仍然在这个问题上磕磕碰碰。今天,我推荐使用debounce,它可以通过RXJS在jQuery、lodash和大多数现代JS框架中使用。

我还在一个应用程序中应用了自动建议,通过remy-sharp具有节流功能。

// https://remysharp.com/2010/07/21/throttling-function-calls
function debounce(fn, delay) {
    var timer = null;
    return function () {
       var context = this, args = arguments;
       clearTimeout(timer);
       timer = setTimeout(function () {
          fn.apply(context, args);
       }, delay);
    };
}

这就是我在keyup上应用的方式,ajax请求将在500(毫秒)后触发,但如果仍然预览请求,则使用中止前一个请求,如下所示:

$('#search').keyup( debounce(function() {
    var currentRequest = null;
    var _q = $.trim( $(this).val() );
    // Only fire if value found in search box
    if( _q.length > 0 ) {
       currentRequest = $.ajax({
           url: '', 
           beforeSend: function() {
               // If found previous ajax request then kill and start new one
               if( currentRequest != null ) {
                   currentRequest.abort();
               }
           }, 
           dataType: 'json'
        });
    }
}, 500) );

使用keyup:

Use keyup():
     $(function () {
    var minlength = 3;
    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();
        if (value.length >= minlength ) {
            $.ajax({
                type: "GET",
                url: "sample.php",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});

而不是像用户键入的那样向服务器发出太多请求。您可以使用setTimeout作为一个选项来限制服务器调用的次数。

但是,如果setTimeout限制太低,甚至在服务器返回您对上一个请求的响应之前,您也可能会触发多个服务器请求。

我建议在keyup事件处理程序中也使用标志。使用setTimeout触发第一个服务器调用后,请等待服务器的响应并设置重置标志。因此,基于此,服务器请求的数量可能会受到限制。

另一种方法是,当第一个keyup事件被触发时。在setTimeout中设置大约1秒的延迟以获得更好的结果。

如果您要获取国家/地区列表或其他名称,该名称取决于搜索关键字的起始字母。在这种情况下,我更喜欢在第一次请求后将数据缓存在客户端中。(如果结果数量较少)。在随后的请求中将过滤客户端中的缓存数据并显示。