[英]Ajax reload page with Rails
I new in rails, and i can't understand how to rewrite next functionality. 我是rails的新手,我无法理解如何重写下一个功能。
For example: I have a list of products. 例如:我有一个产品清单。 And every product has some field ( category ) 每个产品都有一些领域(类别)
def index
if params[:select_query]
@posts = Post.selecting(params[:select_query])
else
@posts = Post.all
end
respond_to do |format|
format.html # index.html.erb
format.js
end
end
Index.html 的index.html
<%= select_tag "credit_card", options_for_select([["first", 1], ["second", 2], ["third", 3]], 2) %>
<div class='tab'>
<%= render 'table' %>
</div>
<%= link_to 'Select', posts_path(select_query: 'first'), class: 'link', remote: true %>
Index.js.erb index.js.erb的
$('.tab').html("<%= j render 'table' %>")
JS JS
$(function(){
$('#credit_card').on('change', function(){
variable = $(this).find('option:selected').text();
$('.link').attr('href', '/posts?select_query='+variable).click();
});
});
I try to realise same functionality but without additional link ( button ) 我尝试实现相同的功能,但没有额外的链接(按钮)
In perfect way i should have only JS file ( with Ajax ) 完美的方式我应该只有JS文件(使用Ajax)
Could help me rewrite this functionality by ajax. 可以帮我改写 ajax的这个功能。
You could try this 你可以试试这个
$('#credit_card').on('change', function(){
var variable = $(this).find('option:selected').text();
$.ajax({
url: '/posts',
data: {select_query: variable },
dataType: 'JS'});
});
Or if you don't want the js.erb at all. 或者如果你根本不想要js.erb。 You can rewrite your controller as: 您可以将控制器重写为:
# ...
respond_to do |format|
format.html # index.html.erb
format.js { render partial: 'table' }
end
And add success handler for your ajax request: 并为您的ajax请求添加成功处理程序:
$.ajax({
url: '/posts',
data: {select_query: variable },
success: function(result) {
$('.tab').html(result);
},
dataType: 'JS'});
你也可以添加success: window.location.reload()
给你ajax调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.