rails通过ajax加载选择选项

时间:2014-11-28 21:21:38

标签: jquery ruby-on-rails ajax select

我有一个关于通过Ajax请求将数据加载到Rails中的select form_helper的问题。

现在,我有一个选择输入字段,在表单中加载大约8000个产品(按用户分组)

因此,完整的http请求和要加载的页面大约需要16秒。它希望页面加载,然后选择输入字段中的选项通过ajax加载记录,这样页面就会加载,直到所有产品都加载完毕。

这是我的选择输入字段:

<%= f.grouped_collection_select(:original_serial_number, 
      @users, 
      :products,
      :display_name, 
      :serial_number, 
      :asset_tag_and_serial_number_and_model, include_blank: true) %>

有关如何做到这一点的任何提示?

由于

2 个答案:

答案 0 :(得分:7)

要通过ajax加载选择记录,我建议你通过json请求来完成。

因此,在您的视图中,您发送传递ID的触发请求:

 <script>
    $(document).ready(function() {

      $('#trigger_select').change(function() {
          $.ajax({
             url: "<%= remote_select_url %>", // this will be routed
             type: 'GET',
             data: {
               send_id: $("#yourIdContainer").val()
             },
             async: true,
             dataType: "json",
             error: function(XMLHttpRequest, errorTextStatus, error){
                        alert("Failed: "+ errorTextStatus+" ;"+error);
                    },
             success: function(data){
                // here we iterate the json result
                for(var i in data)
                {
                  var id = data[i].id;
                  var title = data[i].title;
                  $("#subject_select").append(new Option(title, id));
                }        

             }
           });
        });
      });
  </script>

然后,您必须在routes.rb

上路由您的remote_select操作
  get 'controller/action', :as => 'remote_select'

你的控制器:

  def action
    #filter using id passed by ajax
    @your_model = Your_model.apply_your_filter(params[:send_id]) 
    render json: @your_model
  end 

答案 1 :(得分:0)

既然你要求提示,这是一个想法,我不知道任何可以检测选择字段内部位置的JS事件,所以你可以做的是一个简单的ajax分页。

您可以将隐藏字段中的默认页面值设置为1,如

<%= f.hidden, id: "page", value: 1 %>,让select字段有一个&#34; More&#34;选项,您可以将其放在标记中或作为选择字段旁边的链接。

然后有一个jquery说

$.getJSON("/action/$('#page').val()", function(data) {
    //remove and re render the options 
    $.each(data, function(){
        $("#select_id").append('<option value="'+ this.value +'">'+ this.name +'</option>')
    )
})

并将上面的内容绑定到&#34;点击&#34;功能到或者dom。 并在ajaxSuccess上将隐藏字段的值更改为+1。 在json中发送数据会很好。

相关问题