本文介绍了Rails 3-定期刷新DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AJAX/不引人注目的JavaScript/JQuery刷新div的内容.

I am trying to refresh the contents of a div using AJAX/Unobtrusive JavaScript/JQuery.

如果我创建刷新"链接并为其提供数据远程属性,这很容易做到.

This is easy to do if I make a "refresh" link and give it a data-remote attribute.

但是,我想使用setInterval函数而不是使用链接每2秒刷新一次.

However, I would like to refresh every 2 seconds using the setInterval function rather than using a link.

此代码应演示我正在尝试做的事情.放入application.js时不起作用,因为未评估ERB,但希望它将解释我的目标.

This code should demonstrate what I'm trying to do. It does not work when put in application.js because the ERB is not evaluated, but hopefully it will explain my goal.

  setInterval(function(){
    $("#scuttlebutt").html("<%= escape_javascript(render 'scuttlebutt') %>");
  },2000);

在Rails 3中执行此操作的正确方法是什么?

What would be a proper way to do this in Rails 3??

(我正在使用Rails 3.2.5)

(I am working with Rails 3.2.5)

推荐答案

我最终将代码放到application.js中,该代码将:

I ended up putting code in application.js that would:

  • 检查div是否存在
  • 使用setInterval设置计时器
  • 从Rails的当前URL请求一个js脚本,这将导致对js.erb视图文件的评估.运行此文件后,它将更新我的div.

瞧瞧...

assets/javascripts/application.js

assets/javascripts/application.js

$(function() {

  if ($('#scuttlebutt').length) {
    setInterval(function(){
      $.getScript(window.location.pathname, function(data, textStatus, jqxhr) {
        console.log('Load was performed.');
      });
    },2000);
  }

});

views/tickets/show.js.erb

views/tickets/show.js.erb

$("#scuttlebutt").html(" <%= escape_javascript(render 'scuttlebutt') %>" );

这篇关于Rails 3-定期刷新DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:25