Ajax和Ruby on Rails的简单看法刷新 [英] Ajax with Ruby on Rails Simple View Refresh

查看:182
本文介绍了Ajax和Ruby on Rails的简单看法刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以帮助我一个问题,我有工作了AJAX的一些在Rails中。我想尝试做一些简单的,我只是想不断地检查索引视图的新条目会发生关闭屏幕?

I was wondering if anyone could help me with an issue I'm having working out some AJAX in Rails. I'd like to try and do something simple, I just want to constantly check the index view for a new entry with will happen off screen?

每隔几秒钟这将是非常酷的新条目也只是褪色?新的条目被称为图像一个div类里面,里面是这样的:

Every few seconds it would be really cool for the new entry would just fade in? The new entries are inside a div class called image, and inside that is this:

<%= image_tag image.image_url(:medium).to_s %>

我已经尝试了一些教程,但有些似乎出了一点过我想要实现的日期。我希望有人能帮助我在正确的方向。

I've tried a few tutorials but some seem out of date of a little off what I'm trying to achieve. I hope someone can help me in the right direction.

推荐答案

其基本思想是:

  1. 您存储在某种程度上,都可以访问的JavaScript加载你的最近一次入境,如在数据 - 属性
  2. 您环路Ajax和延时
  3. 通话
  4. Ajax调用的响应会产生变化的DOM
  1. You store your latest entry that's been loaded in some way that is accessible to javascript, such as in a data- attribute
  2. You loop ajax calls with a delay
  3. The response of the ajax call will produce changes in your DOM

查看(图片/ index.html.erb):

1

View (images/index.html.erb):

<% render @images %>

查看(图片/ _image.html.erb):

View (images/_image.html.erb):

<div class="image" data-id="<%=image.id%>">
  <%= image_tag image.image_url(:medium).to_s %>
</div>

2

JavaScript的:

2

Javascript:

function poll(){
  latest_id = $('div.image:first').data('id')
  $.getScript('/images?latest_id='+latest_id)
}

$(function(){setInterval(poll, 5000})

3

控制器:

3

Controller:

@images = Image.order('id desc')
@images = @images.where('id > ?', params[:latest_id]) if params[:latest_id]

查看(图片/ index.js.erb的):

View (images/index.js.erb):

$('div.image:first').before('<%=j render @images%>').hide().fadeIn()

请注意,我做了一些假设有关的型号名称和路径。根据需要,您应该修改路径。

Note that I've made some assumptions about your model name and paths. You should modify the paths as needed.

这例子是用于说明目的,不适合实际应用 - 如果服务器过载时,JavaScript将继续与请求锤打它,或者如果你的初始页面没有初始条目,新条目被插入的方式将打破。

This example is for illustrative purposes and is not suitable for real applications - if the server is overloaded, the javascript will keep hammering it with requests, or if your initial page had no initial entries, the way that new entries are inserted will break.

这篇关于Ajax和Ruby on Rails的简单看法刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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