RoR : form.select + onchange 未将参数中的正确值传递给控制器
我在 Ruby on Rails 表单中有一个选择菜单,定义如下:
<%= f.select :Menu1, [["Option1","value1"],["Option2","value2"]], {}, {:id=>"Menu1_Id", :class => "Menu1_Class"} %>
我正在使用事件处理程序在选择选项时触发控制器操作,并且我想将所选选项的值传递给它
<script type="text/JavaScript" src=http://code.jquery.com/jquery-latest.js">
$(function(){
$('.Menu1_Class').bind('change', function(){
alert($(this).val());
$.ajax('#{:controller => "TestsController", :action => "show"}?param_one='+$(this).val());
});
});
</script>
编辑:这是 js 代码这对我有用,感谢下面 Robin 的回答(请注意,我将它用于操作“get_results”而不是原始的“show”):
<script type="text/JavaScript">
$(function(){
$('.menu_class').bind('change', function(){
$.ajax({
url: "<%= get_results_my_tests_url %>",
data: {
param_one: $(this).val()
}
});
});
});
</script>
在我的控制器中
# GET /tests/1
# GET /tests/1.json
def show
@test = Test.find(params[:id])
if params[:param_one].present?
@blah=params[:param_one]
puts "show : @blah = " + @blah.to_s + "\n"
end
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @test }
end
end
,警报消息包含正确的值(value1 或 value2),但是param_one 不存在,因此 puts 不会为“param_one”返回任何内容,而我希望在那里看到“value1”或“value2”。
任何人都可以指出我哪里做错了吗?
谢谢
I have a select menu in a Ruby on Rails form defined as follows:
<%= f.select :Menu1, [["Option1","value1"],["Option2","value2"]], {}, {:id=>"Menu1_Id", :class => "Menu1_Class"} %>
I am using an event handler to trigger controller action when an option is selected and I want to pass to it the value of the selected option
<script type="text/JavaScript" src=http://code.jquery.com/jquery-latest.js">
$(function(){
$('.Menu1_Class').bind('change', function(){
alert($(this).val());
$.ajax('#{:controller => "TestsController", :action => "show"}?param_one='+$(this).val());
});
});
</script>
EDIT : this is the js code that worked for me thanks to Robin's answer below (notice I'm using it for action "get_results" instead of the original one "show"):
<script type="text/JavaScript">
$(function(){
$('.menu_class').bind('change', function(){
$.ajax({
url: "<%= get_results_my_tests_url %>",
data: {
param_one: $(this).val()
}
});
});
});
</script>
in my controller
# GET /tests/1
# GET /tests/1.json
def show
@test = Test.find(params[:id])
if params[:param_one].present?
@blah=params[:param_one]
puts "show : @blah = " + @blah.to_s + "\n"
end
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @test }
end
end
With this, the alert message contains the right value (value1 or value2) but param_one is not present so puts returns nothing for "param_one", while I expect to see "value1" or "value2" there.
Anyone can please point me to where am I doing something wrong?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的 JavaScript 更改为以下内容:
Change your javascript to the following: