问题
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
回答1:
Change your javascript to the following:
<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>
来源:https://stackoverflow.com/questions/8692353/ror-form-select-onchange-not-passing-the-right-value-in-params-to-the-contro