StackOverflow 中标签的 AutoSuggest 功能如何避免每次击键时进行查询
我正在尝试使用 Jquery 实现类似的功能,例如本网站文本区域下方可用标签的自动建议功能。我试图弄清楚在几次击键之后而不是每次击键之后如何发送请求。我正在使用“keyup”事件来触发我的应用程序上的请求。我意识到这可能会导致服务器点击过多并可能影响性能。
如果有人能解释我如何通过不在每个 keyup 上运行查询来实现 stackOverflow 所做的事情,那就太棒了。
I am trying to implement a similar feature like the autosuggest feature for tags available below the text area on this site using Jquery. I am trying to figure out how the requests are sent after a few keystrokes and not after every keystroke. I am using a 'keyup' event to trigger the request on my app. I was made to realize that this may result in too many server hits and may affect performance.
It would be awesome if some could explain how i could implement the kind of thing stackOverflow does by not having a query run on every keyup.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的一个 Windows 应用程序中有类似的功能。当用户键入字符时,计时器会以 1 秒的间隔启动。在 Tick 事件中,开始搜索。如果用户再次键入,计时器将重新启动。因此,仅当键盘闲置超过一秒时才会执行搜索。
简短的示例(它是用 C# 编写的,但很容易理解):
我没有 Javascript 经验,但是来自
I have a similar feature in one of my windows applications. When the user types a character, a timer is started with a 1 second interval. In the Tick event, the search is started. If the user types again, the timer is restarted. So the search is only performed if the keyboard has been idle for more than a second.
Short sample (it's in C#, but easy enough to follow):
I'm not experienced in Javascript, but the anwswer from here will help you I think:
您所指的方法称为“Debounce”
我通常在所有脚本的底部都有一个“Debounce”函数
然后每当我做任何可以从 debounce 中受益的事情时我都可以通用地使用它
所以您的代码将被编写为
请参阅 Facebook 风格 AJAX 搜索 了解类似的用例...
the method you are referring to is called "Debouncing"
I usually have a "Debounce" function at the bottom of all my scripts
And then whenever I do anything that will benefit from a debounce I can use it generically
So your code would be written as
see Facebook Style AJAX Search for a similar usecase...