页面加载后如何运行Twitter gem [英] How to run Twitter gem after page loads
问题描述
我正在使用 Twitter gem ,但是我希望了解如何在后台运行它页面加载后.
I am using a Twitter gem, however I was hoping to understand how to run it in the background after the page loads.
当前,我需要等待页面呈现,因为gem正在查询某些推文.一旦gem得到响应,页面就会加载.
Currently I need to wait for the page to render, since the gem is working to query some tweets. Once the gem gets its response, the page loads.
但是,我希望在我的Twitter feed"div"标签中显示一个正在加载" GIF,一旦检索到Twitter信息,就用相应的内容替换该GIF.
However, I was hoping to display a "loading" GIF in my Twitter feed "div" tag, and once the Twitter information is retrieved, replace this GIF with the respective content.
我读了几篇文章,介绍如何使用表单以及表单上的":remote => true
"标签,以便进行不会重新加载相应页面的AJAX调用,但是我不想强迫访问者单击链接以查看Twitter推文.
I read several posts how to use a form and the ":remote => true
" tag on the form in order to do AJAX calls that won't reload the respective page, but I don't want to force visitors to click a link in order to see Twitter tweets.
我正在使用:
- Ruby版本:1.8.7
- 导轨版本:3.0.9
推荐答案
可以通过多种方式进行;一种相当普遍的做法以及解决方法是使用jQuery的 $.ajax()
从服务器获取数据并更新页面.
There are multiple ways of doing this; A fairly common practice and the way I would go about this is to use the the jQuery's $.ajax()
to get data from the server and update the page.
客户端:
-
正常加载页面并显示某种加载指示符.
Load the page normally and show some kind of loading indicator.
拨打 $.ajax()
:
$.ajax({
type: "GET",
url: userId + '/tweets', // i.e. tweets is a nested resource of user
success: function(tweets){
$('#loading_indicator').hide();
// Use the tweets that are returned to update the DOM
$.each(tweets, function(ndx, tweet) {
$('#tweet_list').append('<li>'+tweet.body+<'/li'>);
});
}
});
服务器端:
在控制器中有一个动作,该动作将tweet作为JSON发送出去,以供客户端成功回调使用.将此操作的路由设置为与 $.ajax()
中的 url 兼容:
Have an action in a controller that sends out tweets as JSON to be consumed by the client-side success callback. Setup the routing for this action to be compatible with url in $.ajax()
:
class TweetsController < ApplicationController
def show
# collect tweets...
render :json => @tweets
end
end
这篇关于页面加载后如何运行Twitter gem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!