从REST API填充多选select2选项

时间:2017-12-15 03:14:30

标签: javascript jquery ajax rest jquery-select2

我有3个select2字段,我想用API中的AJAX填充它们。我的问题是,如何直接从API填充第一个选择字段选项,然后第二个字段选项也由API填充,但基于我在第一个选择字段中的选择,第三个选项也是如此。

例如,下面是我的代码&数据:

API

[
    {
        "id": 1,
        "project_type": "tv",
        "project_stage": "new",
        "project_name": "Project A"
    },
    {
        "id": 2,
        "project_type": "game",
        "project_stage": "completed",
        "project_name": "Project B"
    },
    {
        "id": 3,
        "project_type": "game",
        "project_stage": "new",
        "project_name": "Project C"
    },
    {
        "id": 4,
        "project_stage": "completed",
        "project_type": "film",
        "project_name": "Project D"
    }
]

HTML

<div class="group">
        <select class="project_type" id="project_type" multiple="multiple">
                <option value=""></option>
        </select>
        <select class="project_status" id="project_status" multiple="multiple"">
                <option value=""></option>
        </select>
        <select class="project_select" id="project_select" multiple="multiple">
                <option value=""></option>
        </select>
</div> 

的Javascript

$('#project_type').select2({placeholder: "Select project type",});
$('#project_status').select2({placeholder: "Select project Status",});
$('#project_select').select2({placeholder: "Select project",});

预期结果:

现在,project_type选择字段会将所有项目类型填充为选项,并说我们选择"game",然后project_status选项将是:

<select class="project_status" id="project_status" multiple="multiple"">
    <option value="completed">Completed</option>
    <option value="new">New</option>
</select>

如果我们选择completed,则第三个过滤器将是:

<select class="project_select" id="project_select" multiple="multiple">
    <option value="Project B">Project B</option>
</select>

我之前从jinja2填充了这个并且它不是动态的,非常感谢任何帮助。

更新:

下面是我当前的代码,由于奇怪的原因,即使是第一个过滤器,即使我获取数据,它也没有填充选项:

        $('#project_type').select2({
            placeholder: "Select project type",
            ajax: {
                url: '/api/filter/',
                delay: 250,
                type: 'GET',
                data: function (params) {
                    var query = {
                      search: params.term,
                      type: 'public'
                    }
                return query
                },
                processResults: function (data) {
                    var data1 = $.map(data, function (obj, idx) {
                        console.log(obj.project_type);
                        return obj;
                    });
                    console.log("processResults2:", data1);
                    return {
                        results: data1,
                      };
                 }
            }
        });

1 个答案:

答案 0 :(得分:3)

这是一个实现Select2 Ajax填充的片段(级联):

&#13;
&#13;
var data = [
    {
        "id": 1,
        "project_type": "tv",
        "project_stage": "new",
        "project_name": "Project A"
    },
    {
        "id": 2,
        "project_type": "game",
        "project_stage": "completed",
        "project_name": "Project B"
    },
    {
        "id": 3,
        "project_type": "game",
        "project_stage": "new",
        "project_name": "Project C"
    },
    {
        "id": 4,
        "project_stage": "completed",
        "project_type": "film",
        "project_name": "Project D"
    }
];

sel_type();
$('#project_status').select2({placeholder: ""});
$('#project_select').select2({ placeholder: ""});

function sel_type() {
  $('#project_type').select2({
      placeholder: "Select project type",
       ajax: {
       type: "POST",
       url: '/echo/json/',
       data: function(params){
         var query={
             message:params.term,
             data: data
         }
         return { json: JSON.stringify( query ) }
       },
       processResults: function (data) {
         var grouped = groupBy(data.data, 'project_type');
         var data1 = [], i = 0;
         for (var k in grouped) {
            data1.push({"id": i++, "text": k})
         }
         return {
           results: data1,
         };
      }
     }
   });
   
   $('#project_type').on('select2:select', function (e) {
      var data = e.params.data;
      console.log(data);
      sel_status(data.text);
  });
}

function sel_status(type) {
   $('#project_status').select2({
      placeholder: "Select project status",
       ajax: {
       type: "POST",
       url: '/echo/json/',
       data: function(params){
         var query={
             message:params.term,
             data: data
         }
         return { json: JSON.stringify( query ) }
       },
       processResults: function (data) {
         var data1 = $.map(data.data, function (obj, idx) {
           if (obj.project_type==type)
 		          return obj;
         });
         var grouped = groupBy(data1, 'project_stage');
         var data1 = [], i = 0;
         for (var k in grouped) {
            data1.push({"id": i++, "text": k})
         }
         return {
           results: data1,
         };
      }
     }
   });
   
   $('#project_status').on('select2:select', function (e) {
      var data = e.params.data;
      console.log(data);
      sel_proj(type, data.text);
  });
 }
 
 function sel_proj(type, status) {
   $('#project_select').select2({
      placeholder: "Select project",
       ajax: {
       type: "POST",
       url: '/echo/json/',
       data: function(params){
         var query={
             message:params.term,
             data: data
         }
         return { json: JSON.stringify( query ) }
       },
       processResults: function (data) {
         var data1 = $.map(data.data, function (obj, idx) {
         	if (obj.project_type==type && obj.project_stage==status) {
             obj.id = obj.id || idx;
             obj.text = obj.project_name;
             return obj;
          }
         });
         return {
           results: data1,
         };
      }
     }
   });
 }
 
 var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
&#13;
select {
  width:200px
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>

<div class="group">
  <select class="project_type" id="project_type" multiple="multiple">
    <option value=""></option>
  </select>
  <br/>
  <select class="project_status" id="project_status" multiple="multiple">
    <option value=""></option>
  </select>
  <br/>
  <select class="project_select" id="project_select" multiple="multiple">
    <option value=""></option>
  </select>
</div>
&#13;
&#13;
&#13;

但由于Ajax请求,它在StackOverflow中不起作用。

工作版本(使用JsFiddle echo)在这里:https://jsfiddle.net/beaver71/4nq62nqo/

P.S。:您必须将Ajax请求中的uri更改为您的,并删除数据POST。