缓存用于加载记录的ajax响应-Rails 3

Cache ajax response for loading records - Rails 3

本文关键字:响应 -Rails ajax 用于 加载 记录 缓存      更新时间:2023-09-26

我有以下代码,它检索当前用户的通知,并在每次通过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 )