加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

select2通过AJAX获取远程数据的方法

发布时间:2020-12-16 03:02:04 所属栏目:百科 来源:网络整理
导读:select2通过AJAX获取远程数据的方法 官方地址:https://select2.org/data-sources/ajax 需要的数据格式是有要求的,如下: { "results": [ { "id": "CA","text": "California" },{ "id": "CO","text": "Colarado" } ],"more": false} 比如我们编写一个python(
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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读