我有一个 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/