缓存用于加载记录的ajax响应-Rails 3
Cache ajax response for loading records - Rails 3
我有以下代码,它检索当前用户的通知,并在每次通过ajax单击#notifications
链接时呈现一个部分。
如何缓存ajax响应,以便在用户第一次单击#notifications
按钮后,同时保持在同一页面上,从缓存中加载结果,而不是每次单击链接时重新检索结果?
notifications.js.coffee
jQuery ->
$("#notifications").click ->
$.ajax
url: "/activities/notifications"
dataType: "html"
type: "GET"
success: (html) ->
$("#notifications-area").html html
我已经尝试添加$.ajaxSetup({"cache":true}),但这加载了两次记录,然后缓存了响应
您可以在html5 中使用localStorage
实现
Notifications = (->
init = ->
get: (user_id) ->
html = localStorage.getItem(user_id)
if html
$("#notifications-area").html html
true
else
false
set: (user_id) ->
$.ajax
url: "/activities/notifications"
dataType: "html"
type: "GET"
success: (html) ->
localStorage.setItem user_id, html
$("#notifications-area").html html
instantiated = undefined
getInstance: ->
instantiated = init() unless instantiated
instantiated
)()
$("#notifications").click ->
Notifications.getInstance().set user_id unless Notifications.getInstance().get(user_id)
当前浏览器支持localStorage
- 即8.0+
- Firefox 3.5+
- Safari 4.0+
- Chrome 4.0+
- 歌剧10.5+
- iPhone 2.0+
- 安卓2.0+
您可以通过使用jquerys data()方法将ajax调用的响应附加到链接来存储,如下所示:
$ ->
$("#notifications").click ->
node = $(this)
if data = node.data('response')
$("#notifications-area").html data
else
$.get("/activities/notifications", (data) ->
node.data 'response', data # this stores the response data for later
$("#notifications-area").html data
所以我走了一条稍微简单一点的路线。当单击#notifications时,我会将一个对象推入一个数组。如果数组的长度小于或等于1,那么我将通过.get()获取通知,反之亦然。
jQuery ->
arr = []
$("#notifications").click ->
arr.push(1)
if arr.length <= 1
$.get("/activities/notifications", (data) ->
$("#notifications-area").html data )
相关文章:
- Rails 4中不执行Ajax响应
- Rails 4远程true和响应js
- Rails-使用ajax改进json响应的处理
- 为什么我的rails应用程序在生产环境中没有正确响应.js格式
- 在 Rails 中,我可以在 JS 响应后在控制器操作中执行 ActionMailer 逻辑吗?
- 如何将 Rails 变量传递给 AJAX 响应函数
- Rails Ajax 表单没有响应
- Rails Application 发送 HTML 响应而不是 JS
- 如何在 Rails 中的 ajax 调用中的 js 响应中包含 html 标记
- Rails 4 - 强制浏览器执行javascript响应而不是显示文本
- rails重定向到格式化html在js中发送响应
- swapImage{src:'image2.jpg'}没有'在Rails 3.1中没有响应
- Twitter Bootstrap Rails按钮下拉列表没有响应AJAX
- 缓存用于加载记录的ajax响应-Rails 3
- 使用rails在javascript响应中呈现Haml文件
- 如何在rails数据库中保存JSON响应的值
- 包含javascript的Rails json响应
- Rails 3原型呈现:更新响应具有text/html内容类型
- 响应格式与rails中的请求不同
- rails 3 javascript未执行,尽管响应的是text/javascript内容类型