select2通过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页面了
服务器类型
$(‘.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
}
});