简体   繁体   English

客户端搜索文本更改-何时发送请求?

[英]Client side search on text change - when to send request?

I have a search engine for an entity, and it has many filters. 我有一个实体的搜索引擎,并且有很多过滤器。 I am required to update the search results when the filters change. 过滤器更改时,我需要更新搜索结果。 Some filters are selected from dropdowns, others are text inputs. 一些过滤器是从下拉列表中选择的,其他过滤器是文本输入。 What is the correct way to implement search on change, when the change can happen frequently as the user types? 当用户输入频繁发生更改时,实现更改搜索的正确方法是什么?

Here are some possibilities: 这里有一些可能性:

  • When the input loses focus. 当输入失去焦点时。 The problem: the user might type away some text and wait for the search to work, but it won't. 问题是:用户可能会键入一些文本并等待搜索工作,但不会。
  • On each keystroke. 每次击键。 The problem is I'll flood the server with requests. 问题是我将向服务器发送请求。
  • Wait x milliseconds after the last change in the input and then send the request. 在输入的最后一次更改之后等待x毫秒,然后发送请求。 The problem is the search might become slow for the user. 问题是用户搜索可能会变慢。

    What is the best approach? 最好的方法是什么?

You can either do keydown or keyup for inputs. 您可以对输入进行键盘按下或键盘按下。 If it's a dropdown menu you can use onchange. 如果是下拉菜单,则可以使用onchange。

Personally, I would recommend adding a minimum character limit so you're not hammering your resources. 就个人而言,我建议添加一个最小字符数限制,以免浪费资源。

For example 例如

var foo = document.querySelector("#inputElement");
// Change your event listener to what you need.
foo.addEventListener("keyup", doSomeStuff);
function doSomeStuff(e){
    var input = e.value;
    // Rest of your function
}

You can learn about event listeners here 您可以在此处了解事件监听器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM