Rails:使用按钮通过Ajax渲染部分

时间:2012-03-02 17:11:30

标签: ruby-on-rails ajax ruby-on-rails-3 jquery

我目前有一个显示微博列表的页面,该页面还包含几个标签,例如Most Recent Most Discussed Most Viewed。我想知道如何在不刷新整个页面和通过ajax的情况下呈现微博的不同类型的列表顺序的最佳方法。我不确定该如何去做,但我愿意学习是否有人借给我帮助。谢谢 :)。到目前为止,我有这么多。

页面HTML

<div id='ContentHeader'>
<%= render 'microposts/new' %>
<div class='StreamTabContainer'>
<ul class='StreamTabs'>
<li class='StreamTab StreamTabRecent active'>
<%= link_to 'Most Recent', some_path, :remote => true, :class => 'TabText' %>
</li>
<li class='StreamTab StreamTabDiscussed'>
<%= link_to 'Most Discussed', some_path, :remote => true, :class => 'TabText' %>
</li>
<li class='StreamTab StreamTabViews '>
<%= link_to 'Most Views', some_path, :remote => true, :class => 'TabText' %>
</li>
<li class='StreamTab StreamTabRated'>
<%= link_to 'Highest Rated', some_path, :remote => true, :class => 'TabText' %>
</li>
</ul>
</div>
</div>


<div id='ContentBody'>
<div id='ajax'></div>
<%= render 'users/microposts', :microposts => @microposts %>
</div>

1 个答案:

答案 0 :(得分:5)

看起来你走的是正确的道路。您的视图在快速浏览时似乎是正确的。

只需要完成这项工作的最后几件,首先要确保您的控制器可以接受js调用:

 # Inside Controller's action
 respond_to do |format|
     format.js
 end

设置完成后,您需要创建javascript以便为每次调用返回客户端。在视图文件夹中创建文件

 # app/views/controllerName/actionName.js.erb
 $('#ajax').html("<%= escape_javascript(render(:partial => 'content', :sortingType => 'type')) %>");

以上将允许您呈现显示帖子的部分(在此示例中我将其命名为内容),并将sortedType的局部变量传递给partial。该响应将放在div id =“ajax”的html中(来自您的示例)。最后一步是创建视图部分,它将按照您希望的方式对所有帖子进行排序

# app/views/resourceName/_content.html.erb
# Simply create your view partial here, which uses the :sortingType to display your posts in the order you need

希望这会让你更接近你的意图。

编辑:已实现我的引号存在一些问题。

相关问题