Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 实时刷新Rails视图_Javascript_Ruby On Rails 3_Real Time - Fatal编程技术网

Javascript 实时刷新Rails视图

Javascript 实时刷新Rails视图,javascript,ruby-on-rails-3,real-time,Javascript,Ruby On Rails 3,Real Time,我有一个Rails 3.2.14遗留应用程序,在其中我有一个视图,我希望在不重新加载页面的情况下刷新其中的部分。我目前有这个工作,但我想看看这是否是最好的方式去做 下面是代码摘录: index.html.erb: <div id="active"> <%= render "assigned_calls" %> </div> <div id="inactive"> <%= render "unassigned_calls" %>

我有一个Rails 3.2.14遗留应用程序,在其中我有一个视图,我希望在不重新加载页面的情况下刷新其中的部分。我目前有这个工作,但我想看看这是否是最好的方式去做

下面是代码摘录:

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>

$(函数(){
setInterval(函数(){
$.getScript(“/calls”).fail(函数(jqxhr、设置、异常){
window.location=“/users/sign_-in?duplicate_session=true”;
});
}, 10000);
});
index.js.erb

$("#active").html("<%= escape_javascript render("assigned_calls") %>");
$("#inactive").html("<%= escape_javascript render("unassigned_calls") %>");
$(“#活动”).html(“”);
$(“#不活动”).html(“”);
到目前为止,我每10秒有一个JS调用要获取/调用。这很好,但我想知道是否有更好的方法来做到这一点。在视图中,我们有一个计时器(评估调用日期与Time.zone.now的关系),它在部分重新加载后每10秒更新一次。我真的希望这是真正的实时,不知道是否会建议将JS中的间隔设置为1秒。这似乎需要大量的部分刷新和大量的查询/日志条目


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

也许您可以使用新功能:

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

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
class SensorController

您可以在以下链接中找到:

您可以使用websockets和Redis pubsub机制来动态更新Rails部分,而不是每10秒创建一次AJAX请求。这里有一个gem可以帮助您实时刷新div:


这里有一篇关于Rails和使用WebSockets和JS框架的实时更新的文章(还有其他选择):只是一些疯狂的想法:?或根据你的应用程序的不同,这可能比预期的要多。@MarcoCI我昨晚实际上在看同一篇文章。我不确定我是否想遇到这些麻烦,因为我最终将在Rails 4.x.x中重新编写应用程序,我相信它支持实时事件/消息。目前正在为我的3.2.14旧版应用程序寻找一种更“实时”的方法。@MarcoCI说得对——websockets是最好的解决方法。PubNub和类似的第三方服务工作得非常好。我不确定Rails4中的什么可以解决您的问题。您不必升级到Rails4.x.x:只需使用WebSocket(如Socket.IO或SockJS)实现即可。