简体   繁体   English

Rails / JS - 在没有页面刷新的情况下获取变量

[英]Rails/JS - get variable without page refresh

In my app I have a variable which is an integer. 在我的应用程序中,我有一个变量,它是一个整数。 The variable is constantly changing and I want it to always show the current integer when a user is on the site without them having to keep refreshing the page. 变量不断变化,我希望它总是在用户在网站上时显示当前整数,而不必不断刷新页面。

I know there are a few ways to do this, but what would be the easiest and most unobtrusive way to accomplish this? 我知道有几种方法可以做到这一点,但是最简单,最不引人注目的方法是什么呢?

For easy sake lets make this the integer 为了方便起见,我们将其作为整数

@foo = Post.all

I would supply some code but after research elsewhere I still haven't been able to try and solve this. 我会提供一些代码,但经过其他地方的研究,我仍然无法尝试解决这个问题。

Thanks. 谢谢。

As far as I know, server can't send information to client without request from client. 据我所知,服务器无法在没有客户请求的情况下向客户端发送信息。 So, you can set up regular AJAX requestes for that. 因此,您可以为此设置常规的AJAX请求。 Firstly, you should make separate action in controller, that return your integer in json 首先,您应该在控制器中单独执行操作,在json中返回整数

def foo_update
  @foo = some_new_value
  render json: @foo
end

In you .js files set Interval and AJAX request 在你.js文件中设置Interval和AJAX请求

var ajax_foo_update = function(){
  $.get("/controller_name/foo_update",function(data){
     $("#elem_to_place_foo").html(data.integer);
  });
}
$(function(){
  setInterval(ajax_foo_update, 10000);
});

This function will be updating foo every 10 seconds. 此功能将每10秒更新一次foo。 Also, you @foo should look somehow like {integer: 5} Don't forget to write right routes. 另外,你@foo应该看起来像{integer:5}不要忘记写正确的路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM