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. Firstly, you should make separate action in controller, that return your integer in json
def foo_update
@foo = some_new_value
render json: @foo
end
In you .js files set Interval and AJAX request
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. Also, you @foo should look somehow like {integer: 5} Don't forget to write right routes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.