当有新记录要自动显示时,如何在Ruby on Rails视图中刷新表 [英] How To refresh a table in a Ruby on Rails view when there are new record to show automatically
问题描述
感谢您抽出宝贵的时间阅读本文!
Thanks for taking the time to read this!
好吧,这就是我要做的事情,我有Rails应用程序,该应用程序显示一个表,该表显示了数据库中的一些信息,并且我需要它来自动重新加载表(如果可能的话,可以进行部分重新加载,所以我不这样做)不必重新加载整个页面.)将新数据添加到数据库时.
Well, this is what I am trying to do, I have Rails app that displays a table displaying some information in the database, and I need it to automatically reload the table (if possible in a partial reload, so I don't have to reload the whole page.) When new data is added to the database.
预先感谢!
推荐答案
为使表数据可以重新加载,您必须首先通知客户端内容已更改,然后实际重新加载内容.为此,您必须在客户端使用Javascript/Ajax:
So that the table data can reload, you'll have first to notify th client the content has changed, then actually reload the content. To achieve that you'll have to use Javascript/Ajax on the client side :
- 向您的控制器添加一个操作,该操作将返回最近一次更新的操作 JSON中的时间戳
- 将时间戳存储在JS变量中
- 每n秒调用一次操作,以便您可以比较本地和远程时间戳记
- 使用Ajax将表部分替换为更新的表
- add an action to your controller that returns the last updated timestamp in JSON
- store the timestamp in a JS variable
- every n seconds call the action so that you can compare the local and remote timestamps
- use Ajax to replace your table partial with the updated one
jQuery随Rails一起提供,将非常有效地处理Ajax部分.请参见 jQuery.ajax 和
jQuery ships with Rails and will handle the Ajax part very efficiently. See jQuery.ajax and jQuery.replaceWith to replace the old content with the new one.
在提供表的控制器操作上,使用一个参数,以便从Ajax调用时可以禁用布局呈现.这样,控制器将仅提供相关内容(包含表的视图).
On the controller action that provides the table, use a parameter so that you can disable the layout rendering when called from Ajax. This way the controller will only provide the relevant content (the view containing table).
这篇关于当有新记录要自动显示时,如何在Ruby on Rails视图中刷新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!