将 jQuery remove() 与缓存页面一起使用(Rails 后端)
我正在使用 jQuery 和 Rails 3 后端,我有以下场景:
- 用户看到他们帖子上的评论并想要删除它
- 用户单击删除按钮并从数据库中删除评论
- jQuery 使用
remove()< /code> 从 DOM 中删除该项目,作为对上述步骤 2 的 AJAX 成功响应
- 用户导航到不同的页面
- 用户点击后退按钮返回带有评论的页面
- 旧评论仍然存在,尽管它已被删除从服务器和 DOM 中删除
这种情况下的注释显然是由浏览器缓存的,因此即使它之前已被删除(并且它也不存在于服务器上),它也会显示出来。
当用户点击后退按钮时,如何防止显示评论(或已从 DOM 中删除的先前缓存对象)?
顺便说一句:请不要说“不缓存任何页面”:) 这不是一个选项。
I'm using jQuery with a Rails 3 backend and I have the following scenario:
- User see's a comment on their post and wants to delete it
- User clicks the delete button and deletes the comment from the database
- jQuery uses
remove()
to remove the item from the DOM as an AJAX success response to step 2 above - User navigates to a different page
- User hits the back button to go back to the page with the comment
- The old comment is still there, even though it was removed from the server and from the DOM
The comment in this scenario is obviously being cached by the browser and so it shows up even though it was previously deleted (and it doesn't exist on the server either).
How do you prevent the comment (or prior cached objects that have been removed from the DOM) from showing up when the user hits the back button?
By the way: Please don't say, "don't cache any pages" :) That is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在使用 Rails 页面缓存,那么您应该在创建、更新和删除操作中清除它。有关更多详细信息,请参阅链接
if you are using rails page cache then you should clear it on Create, Update and Delete actions. see link for more details
答案一:如果用户使用后退按钮,那么当他们看到过去的事情时,他们不应该感到惊讶。
答案二:这有点繁琐,但您可以尝试在
$(document).ready()
中进行 ajax 调用来检查是否有过时的内容。我不确定这是否有效。如果没有,您可以设置对服务器进行 ping 操作的时间间隔,以仔细检查屏幕上没有过时的内容。 (我的 ping 频率高达 7 秒,性能良好)我不认为有一种非繁琐的方法可以做到这一点(除了防止缓存;)
Answer One: If a user is uses a back button, they shouldn't be surprised when they see things from their past.
Answer Two: It's a little heavy handed, but you could try an ajax call in
$(document).ready()
that checks for outdated content. I'm not certain that would work. If not, you could set up an interval the ping to server to double check there's no outdated content on the screen. (I've had good performance with pings as frequent as 7 seconds)I don't think there is a non-heavy handed way to do this (other than preventing caching ;)
我不知道它何时取决于浏览器,并且可能会破坏您的 RESTful 路由,但您可以做的是向帖子源自的相同 URL 发出 PUT/POST,并在AJAX 响应禁用缓存(使用 Cache-Control 标头)。它应该使浏览器缓存中的该 URL 无效,因为浏览器通常不会区分使用 HTTP 动词。
I don't know whenever it depends on browser, and it may break your RESTful routes, but what you can do, is issue a PUT/POST to the same URL the post originated from, and in the AJAX response disable caching (using the Cache-Control header). It should invalidate this URL in the browser's cache, as browsers usually don't discriminate using HTTP verbs.