我在 Ruby on Rails 表单中有一个选择菜单,定义如下:
<%= f.select :Menu1, [["Option1","value1"],["Option2","value2"]], {}, {:id=>"Menu1_Id", :class => "Menu1_Class"} %>
我正在使用事件处理程序在选择选项时触发 Controller 操作,并且我想将所选选项的值传递给它
<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>
编辑:由于下面 Robin 的回答,这是对我有用的 js 代码(请注意,我将它用于操作“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>
在我的 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
这样,警报消息包含正确的值(value1 或 value2),但 param_one 不存在,因此 puts 不会为“param_one”返回任何内容,而我希望在那里看到“value1”或“value2”。
谁能指出我哪里做错了?
谢谢
最佳答案
将您的 JavaScript 更改为以下内容:
<script type="text/JavaScript" src=http://code.jquery.com/jquery-latest.js">
$(function(){
$('.Menu1_Class').bind('change', function(){
alert($(this).val());
$.ajax({
url: "<%= test_path(@test) %>",
data: { param_one: $(this).val() }
});
});
});
</script>
关于jquery - RoR : form. select + onchange 未将参数中的正确值传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8692353/