更新一个Rails 3部分使用AJAX(而不是形式) [英] Update a Rails 3 partial using AJAX (not a form)

查看:63
本文介绍了更新一个Rails 3部分使用AJAX(而不是形式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些关于提交表单后更新使用Ajax局部的问题和答案。但我的问题是?简单?我只是想重装部分每隔几秒钟和负载在新的数据。这实在不能硬可言,我记得在做类似的事情在Rails的2.3,但我无法找到答案的任何地方。

I found a number of questions and answers regarding updating a partial using Ajax after submitting a form. But my question is ?simpler?, I just want to reload a partial every few seconds and load in the new data. This really can't be hard at all, and I remember doing something similar in Rails 2.3 but I can't find the answer anywhere.

基本上,我有一个show.html.erb渲染的部分,像这样:

Basically, I have a show.html.erb rendering a partial like so:

<div id="latest_post">
    <%= render :partial=>'info/latest', :object=>@user, :as=>:user %>
</div>

位于应用程序/视图/信息的部分文件/ _latest

The partial file located at app/views/info/_latest

<% post = user.posts.last %>
<h1>Last Post</h1>
<p><%= post.content %></p>

我只想latest_post div来进行每30秒更新一次。请帮帮忙!

I just want the latest_post div to be updated every 30 seconds. Please help!

推荐答案

那么事实证明,答案是一个有点复杂:

Well it turns out the answer is a little complicated:

第1步:使用JavaScript的的setInterval 随着jQuery的 $得到()功能函数加载一个页面,说 /用户/ 1 /职位/最新

Step 1: Use Javascript's setInterval function along with jQuery's $.get() function to load a page, say /users/1/posts/latest.

setInterval(function(){
  $.get("/users/1/posts/latest.js", function(data){
    $("latest_post").html(data);
  },
  "html")
}, 30000);

第2步:创建一个 latest.js.erb 键,把它放在你的应用程序/视图/帖文件夹

Step 2: Create a latest.js.erb and put it in your app/views/posts folder.

目录 latest.js.erb

<%= render partial: 'posts/latest', object: @user.posts.last, as: :post %>

第3步:创建上述部分与任何你想(如果你不需要的部分,你可以只写div的全部内容在 latest.js.erb 文件。)

第4步:添加最新的方法,你的 PostsController ,它定义 @user 等为 latest.js.erb 来使用。

Step 4: Add a latest method to your PostsController, that defines @user, etc. for the latest.js.erb to use.

第五步:添加得到'/最新的 routes.rb中

这篇关于更新一个Rails 3部分使用AJAX(而不是形式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆