select2通過AJAX獲取遠程數據的方法
阿新 • • 發佈:2018-09-18
param ajax typename more clas model gin all mode select2通過AJAX獲取遠程數據的方法
官方地址:https://select2.org/data-sources/ajax
需要的數據格式是有要求的,如下:
{
"results": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colarado"
}
],
"more": false
}
比如我們編寫一個python(Django)來實現:
class ApiWorkTicketEcsGetType(LoginRequiredMixin, View): def get(self,request): datalist = [] t = models.AliEcsType.objects.all().values(‘alitypeid‘,‘typename‘) for i in t: ret = {} ret[‘id‘]= i[‘alitypeid‘] ret[‘text‘] = i[‘typename‘] + ‘-‘ + i[‘alitypeid‘] datalist.append(ret) return HttpResponse(json.dumps({‘results‘:datalist,‘more‘:‘false‘}), content_type=‘application/json‘)
然後我們就可以編輯HTML頁面了
<div class="form-group"> <label class="col-sm-3 control-label no-padding-right">服務器類型</label> <div class="col-sm-5"> <select class="js-data-example-ajax form-control"></select> </div> </div> <script type="application/javascript"> $(‘.js-data-example-ajax‘).select2({ ajax: { url: ‘{% url ‘api_workticket_getecstype‘ %}‘, dataType: ‘json‘, // Additional AJAX parameters go here; see the end of this chapter for the full code of this example } }); </script>
select2通過AJAX獲取遠程數據的方法