无需更新整个页面即可访问更新的数据

问题描述 投票:0回答:1

我有一个Person模型,其位置每隔几秒钟就会从移动应用程序中更新一次并保存到数据库中。现在,我想在视图中访问更新的信息,而无需重新呈现整个页面。

我该怎么做?

我想做这样的事情

setInterval(function(){
  // display updated data
}, 5000);

p.s .:我仅在时间间隔内使用JavaScript,这是一个Rails问题。

每隔几秒钟重新加载页面即可,但是完全杀死了我想做的事情。

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

使用ajax请求获取数据。假设您要更新的div具有ID current-location,您可以执行...

setInterval(function() {    
  $.ajax({
    type: 'POST',
    url: "/people/<%[email protected]%>/get_location",
    success: function(data) {
      $('#current-location').html(data.location);
    }
  });
}, 5000);

在routes.rb中定义一个成员路径

resources :people 
  member do
    post :get_location
  end
end

然后在您的PeopleController中创建一个名为get_location的动作,并确保最后一行类似于...

person_location = get_location # some method that returns location
render json: {location: person_location}
© www.soinside.com 2019 - 2024. All rights reserved.