使用Ajax在Django中填充下拉列表

时间:2020-03-13 06:47:00

标签: django ajax

我的表单中有几个下拉菜单,我希望使用后端的Ajax来填充。下面给出了相关的代码段:

HTML:

<div class="row">
          <div class="col-xs-6">
              <div class="col-xs-6">
                    <label name="start_date" class="control-label" style="width:35%">Start date</label>
                    <input type="date"  style="color:black;width:100px" ></input>
      </div>
      </div>
      <div class="col-xs-6">
          <label name="end_date" class="control-label" style="width:35%">End Date(Default: Current Date)</label>
          <input style="color:black;width:100px" type="date"></input>

      </div> 
    </div>
    <div class="row">
      <div class="col-xs-6">
         <label name="fruit" class="control-label" style="width:35%; padding-left:15px">Select a Fruit</label>
          <select style="width:150px;height:30px">
            {% for option in options.fruit %}
              <option value="{{ option }}">{{ option }}</option>
            {% endfor %}
          </select>
      </div>
      <div class="col-xs-6">
          <label name="vendor" class="control-label" style="width:35%">Select a vendor</label>
          <select style="width:150px;height:30px">
            {% for option in options.vendor %}
              {{ option }}
              <option value="{{ option }}">{{ option }}</option>
            {% endfor %}
          </select>             
      </div> 
    </div>
{% block script %}
<script>
document.onload = function(){
    $.ajax({
        url : window.location.href,
        type:'GET',
        cache:false,
        data:{type:'formdata'},
        success:function(res){
            if(typeof res.options == 'undefined'){
                self.options = res.options;
            }
            if(typeof res.options.start_date == 'undefined'){
                self.form.start_date = res.options.start_date;
            }
            if(typeof res.options.end_date == 'undefined'){
                self.form.end_date = res.options.end_date;
            }
            if(typeof res.options.fruit == 'undefined'){
                window.fruit = res.options.fruit;
            }
            if(typeof res.options.vendor == 'undefined'){
                window.vendor = res.options.vendor;
            } 
        },
        error : function(err){
            self.message = "Error getting data for the form";
        }
    });
}
</script>
{% endblock %}

下拉菜单彼此独立。通过此视图在前端提供数据:

class Search(View):
    def get(self, request):
        if request.GET.get('type') == 'formdata':
            options = {'fruit': [], 'vendor': []}
            try:
                cursor = connections['RDB'].cursor()
                options['end_date'] = today.strftime('%Y-%m-%d')
                last_week_date = today - timedelta(days=7)
                options['start_date'] = last_week_date.strftime('%Y-%m-%d')
                options['fruit'] = [a[0] for a in cursor.fetchall()]
                options['vendor'] = [a[0] for a in cursor.fetchall()]
                return JsonResponse({'options': options})

后端工作正常,选项字典正按我的预期填充。但是,下拉选项未在前端显示。我要去哪里错了?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许尝试使用select2,它是一个非常好的工具,可以通过Ajax填充选择框,甚至内置了搜索功能。这是一个简单的例子。

html-

<html>
  <head>
    <title>Using Select2</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <div class="jumbotron">
      <div class="container bg-danger">
        <div class="col-md-6">
          <label>Single Select2</label>
          <select class="js-data-example-ajax"></select>
        </div>
     </div>
    </div>

    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Select2 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script>

$('.js-data-example-ajax').select2({
  ajax: {
    url: 'https://api.github.com/search/repositories',
    dataType: 'json'
    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
  }
});

    </script>
  </body>
</html>

别忘了导入相对的JS和CSS CDN。