【问题标题】:RoR : form.select + onchange not passing the right value in params to the controllerRoR:form.select + onchange 没有将参数中的正确值传递给控制器
【发布时间】:2012-01-01 08:10:52
【问题描述】:

我有一个 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>

编辑:感谢 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>

在我的控制器中

# 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”。

谁能指出我哪里做错了?

谢谢

【问题讨论】:

    标签: jquery select controller action params


    【解决方案1】:

    将您的 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>
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多