javascript - 实时刷新 Rails View

标签 javascript ruby-on-rails-3 real-time

我有一个 Rails 3.2.14 遗留应用程序,我有一个 View ,我想在不重新加载页面的情况下刷新部分 View 。我目前正在进行这项工作,但我想看看这是否是最好的方法。

以下是代码摘录:

index.html.erb:

<div id="active">
  <%= render "assigned_calls" %>
</div>

<div id="inactive">
  <%= render "unassigned_calls" %>
</div>


<script>
  $(function() {
    setInterval(function(){
      $.getScript("/calls").fail(function(jqxhr, settings, exception) {
        window.location = "/users/sign_in?duplicate_session=true";
      });
    }, 10000);
  });
</script>

index.js.erb

$("#active").html("<%= escape_javascript render("assigned_calls") %>");
$("#inactive").html("<%= escape_javascript render("unassigned_calls") %>");

到目前为止,我每 10 秒就有一次 JS 调用来获取/calls。这工作得很好,但我想知道是否有更好的方法来做到这一点。在 View 中,我们有一个计时器(评估调用日期与 Time.zone.now),自部分重新加载以来,它每 10 秒更新一次。我真的希望这是真正实时的,并且想知道是否建议将 JS 中的间隔设置为 1 秒。这看起来像是大量的部分刷新和大量的查询/日志条目。

如果有更好的方法来实时刷新 div,我洗耳恭听。现在我所拥有的有效,但我的最终目标是让数据以某种方式实时更新。

最佳答案

也许你可以使用新功能:

ActionController::Live

他的模块由 Aaron Patterson 开发,使数据能够从服务器实时流式传输到客户端。本质上,ActionController::Live 不是返回 html 或 JSON 作为对 html 请求的响应,而是支持将 i/o 流作为响应返回。这意味着我们可以在 Controller 中定义一个操作,该操作将向任何请求它的客户端设置实时数据流,直到连接再次关闭。

class SensorController < ApplicationController

 include ActionController::Live

 def temperature

   response.headers['Content-Type'] = ‘text/event-stream’

   100.times {

     response.stream.write(“The temperature is #{ 100*rand} degrees Celcius\n”)

     sleep 0.5

   }

   response.stream.write(“That’s all for now!”)

 ensure

   response.stream.close

 end

end

您可以通过此链接找到:http://api.rubyonrails.org/classes/ActionController/Live/SSE.html

关于javascript - 实时刷新 Rails View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25263779/

相关文章:

javascript - 主体背景与模态窗口重叠如何解决?

ruby-on-rails - 在产品中生成 .zip 文件的问题 (Rails 3)

python - 哪些基于 python 的 ajax 推送服务器适合使用

linux - 非 RTOS 上的抢占式任务

javascript - 从 localStorage 存储和加载下拉选择

javascript - 如何强制网站使用最新版本的 CKEditor.js 和用户脚本?

javascript - 将数组转换为用方括号 [ ] 括起来的对象

ruby-on-rails - Ruby on Rails 中 <%= ... %> 和 <% ... %> 有什么区别

ruby-on-rails - 在任何来源中均找不到 capistrano-2.13.3

c++ - Linux C++用户空间应用程序实时休眠功能(POSIX、Raspberry Pi)