html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="/static/js/jquery-2.1.0.js"></script> <link rel="stylesheet" href="/static/css/select2.min.css"> <script type="text/javascript" src="/static/js/select2.full.js"></script> <script type="text/javascript" src="/static/js/json2.js"></script> </head> <body> <div> <div class="mycontainer"> <table width="50%"> <tr> <td width="50%">组: <select id="group" name="group" style="width: 70%"> </select> </td> <td width="=50%">成员: <select id="tester" name="tester" style="width: 70%"> </select> </td> </tr> </table> </div> </div> </body> </html>javascript:
<script> $('#group').select2({ placeholder: 'select a group', ajax: { url: "/group", dataType: 'json', processResults: function(data) { return { results: $.map(data, function(item) { return { text: item.text, id: item.id } }) }; }, } }); $('#tester').select2({ placeholder: 'select a tester' }); // group被选择时,tester从后台获取数据并展示到前端 $('#group').on('select2:select', function(evt) { //清空select2的options $("#tester").empty(); $('#tester').select2({ placeholder: 'select a tester', ajax: { url: "/tester", type: 'get', dataType: 'json', data: { 'group': $("#select2-group-container").html() }, processResults: function(data) { return { results: $.map(data, function(item) { return { text: item.text, id: item.id } }) }; }, } }); }); </script>效果如下:
参考文章: http://select2.github.io/examples.html#events