[英]Rails implementation of input tag firing event on value change
I was wondering if there is some cleaner way to implement event firing on input
tag value change (i want it to fire every time character is entered/deleted) and make these values visible in controller other than using ajax? 我想知道是否存在一些更清洁的方法来实现对
input
标签值更改的事件触发(我希望每次输入/删除字符时都会触发)并使这些值在控制器中可见而不是使用Ajax?
So the way I know now is implementing JavaScript snippet which would attach addEventListener
to input
element (like here ) and would make ajax call to initial rails controller to pass the new input
tag value. 因此,我现在所知道的方式是实现JavaScript代码段,该代码段将
addEventListener
附加到input
元素(如here ),并将对初始rails控制器进行ajax调用以传递新的input
标签值。 However ajax feels like too much as opposed to if there would be something native in rails, I just can't seem to find it. 但是ajax感觉太多了,而不是在rails中有一些本机的东西,我只是找不到。
If you need anything from browser going out to server (written in any language) without refreshing the page, Ajax
is the way to go. 如果您需要从浏览器到服务器(以任何语言编写)的任何内容而无需刷新页面,则
Ajax
是您的理想之选。 Now-a-days, fetch
would be another alternative, which works in similar manner. 如今,
fetch
将是另一种替代方法,其工作方式类似。
If you need every key-stroke to be sent to server (controller), you should add a keyup
event listener. 如果需要将每个击键发送到服务器(控制器),则应添加一个
keyup
事件侦听器。 In the event listener function, make an Ajax/fetch call to the endpoint, and return relevant information from your controller. 在事件侦听器功能中,对端点进行Ajax / fetch调用,然后从控制器返回相关信息。
Do remember to include a timestamp in the requests, and send them back in response though. 请记住在请求中包含时间戳,然后将其发送回以作为响应。 In most such scenarios, you'd want to be differentiate between "what is new" vs "what is stale", in case user types too fast.
在大多数此类情况下,如果用户输入速度太快,则希望区分“什么是新内容”与“什么是旧内容”。 Due to network delays, responses typically do not come back in same order as the requests were made in.
由于网络延迟,响应通常不会以发出请求的顺序返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.