![](/img/trans.png)
[英]Updating the values of rails instance-variables in a view after updating them in the controller using an AJAX call
[英]Rails View not updating after jQuery Ajax call
我处于第一个Rails项目的中间,已经到达要根据SELECT
标记的值更改模型索引的ORDER BY
的阶段。
我的index.html.erb中有以下onchange
<div id="sortBy">
<span>Sort by:</span>
<%= select_tag "sort_by", options_for_select([ "Newest first", "Oldest first" ], "Newest first"), { :onchange => "changeSortOrderJs(this.value)" } %>
</div>
那应该更新:
<% @horses.each do | horse | %>
<%= horse.name %>
<% end %>
这将在我的coffeescript资产中调用以下方法(由于是anon函数,因此带有@前缀):
@changeSortOrderJs = (val) ->
$.ajax
type: 'GET'
url: '/horses'
data: order: val
这映射到我在HorsesController中的索引动作
def index
order = params[:order]
if(order == nil)
order = 'Newest first'
end
@horses = Array.new
if order == 'Newest first'
@horses = Horse.all.order("created_at DESC")
elsif order == 'Oldest first'
@horses = Horse.all.order("created_at ASC")
end
//tried this later but didn't work either
respond_to do |format|
format.html
end
end
我可以在我的development.log中看到它正在工作,并且以正确的顺序填充@horses。 但是视图不会刷新。
如果我使用respond_with(@horses)
,然后在ajax调用中成功回调,即
@changeSortOrderJs = (val) ->
$.ajax
type: 'GET'
url: '/horses'
data: order: val
success: (result) ->
$('body').html(result)
然后它确实起作用,并且马重新排序。 但是我宁愿不这样替换整个身体。
我认为实例变量的全部意义在于您可以重新定义它们,并且视图将自动更新?
实例变量不仅可以神奇地更新页面。 您必须像在代码的最后一部分中一样使用成功函数。 如果您想即时更新,则应该使用Knockout.js或类似的东西
另外,如果您打算渲染局部图像,则必须在Coffeescript文件之外进行。 例如,在您的控制器中执行以下操作:
respond_to do |format|
format.js
end
而app / controllers / horses / index.js可以:
container = $('#your_div_here');
<% @horses.each do |horse| %>
container.prepend( "<%= j render( :partial => 'horses/horse', :locals => { :horse => horse } ) %>" );
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.