使用ajax每X秒更新html页面

5
我看到有人发帖讨论此问题:每隔x秒自动刷新Html表格
现在,我正在使用Rails,并且想做同样的事情,但我想告诉Rails我想要一个远程页面,我不想加载完整页面。 我只想模拟:remote => true操作与Ajax。 我已经尝试了普通的Ajax,但Rails会加载整个页面而不是我想要的相关内容。
我该怎么办?
3个回答

6
你的代码应该像这样:

你的控制器

def your_action
 # your code goes here
end

(your_action.js.erb)

$("#div_id").html("<%= escape_javascript reder :partial => "your_partial_for_table" %>")

your_action.html.erb

<div id="div_id">
 <%= render :partial => "your_partial_for_table" %>
</div>

_your_partial_for_table.html.erb

#your table goes here

<script>
  $(function() {
    $(document).ready(function() {
      setInterval(function() {
        jQuery.ajax({
          url: "<path to your_action>",
          type: "GET",
          dataType: "script"
        });
      }, 30000); // In every 30 seconds
    });
  });
</script>

@algorhythm:嘿,实际上这对我有用,试试看。我已经使用它来自动显示通知,并设置了每30秒的时间间隔。 - siv rj

2

服务器发送事件

您可能希望使用服务器发送事件(来自HTML5)

服务器发送事件(SSE)是一种技术,通过HTTP连接,浏览器可以从服务器自动获取更新。服务器发送事件EventSource API已经作为HTML5的标准之一由W3C进行了规范1

这基本上会启动一个叫做Ajax长轮询的东西,其中您的JS将每秒或每几秒“ping”一个特定的URL。然后Ajax轮询请求将从服务器返回特定的响应,使您可以根据需要使用。

--

布局

我会这样做:

#app/assets/javascripts/application.js
var source = new EventSource('path/to/your/endpoint');
source.addEventListener('message', function(e) {
      //do something here
}, false);

#app/controllers/your_controller.rb
Class YourController < ApplicationController
   include ActionController::Live

   def your_action
       response.headers['Content-Type'] = 'text/event-stream'

       sse = Reloader::SSE.new(response.stream)
       begin
           sse.write(last_updated, event: 'results')
       rescue IOError
          # When the client disconnects, we'll get an IOError on write
       ensure
         sse.close
       end
   end
end

这里的技巧在于SSE使用自己的内容类型-text/event-stream来接收和解析所需的数据。这与规定典型HTTP协议的标准mime类型进行比较。
我使用了此URL作为参考 - 然后您可以在从服务器返回的文本上进行操作!

0
/* with jQuery */
jQuery(documenta).ready(function() {
    setTimeout(function() {
        jQuery('.table').load(...);
    , 5000);
});

# with rails, determine if it is a ajax request
if request.xhr?
    # respond to Ajax request
else
    # respond to normal request
end

请参见此处{{link1:Rails检测请求是否为AJAX}}


Rails 会知道这是一个远程请求吗?这就是我在另一条评论中看到的,但它并没有帮助,因为它会加载整个页面。 - gal
我不确定你的意思。Rails为什么需要知道它是否是远程请求?每个请求都是远程请求,不是吗?你想知道它是否是ajax请求,对吧?看解决方案... - algorhythm
我的意思是,我希望它的行为就像一个带有:remote => true的Rails链接。 - gal
看一下这个:https://dev59.com/LWzXa4cB1Zd3GeqPQimS - algorhythm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接