Django:如何创建从属下拉列表

时间:2019-06-04 20:44:50

标签: python ajax django

我想创建相关的下拉菜单,但是我不确定如何最好地实现该解决方案。基于在第一个下拉菜单中选择的值,我想在查询中使用该值填充后续的下拉菜单。尽管我已经完成工作,但在第一个下拉菜单中选择一个值后,我没有返回任何数据。请告知我是否还有其他信息可以更好地说明我的问题。

Models.py

class Location(models.Model):
    city = models.CharField(max_length=50)
    company = models.ForeignKey("company", on_delete=models.PROTECT)

    def __unicode__(self):
        return u'%s' % self.name


class Company(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s' % self.name

Views.py

def opportunities(request):
    companies = cwObj.get_companies()
    context = {'companies': companies}
    return render(request, 'website/opportunities.html', context)


def new_opportunity(request):
    source = request.GET.get('selected_company')
    result_set = []
    all_locations = []
    string = str(source[1:-1])
    selected_company = cwObj.get_locations(string)
    all_locations = selected_company
    for location in all_locations:
        result_set.append({'location': location})
    return HttpResponse(json.dumps(result_set), mimetype='application/json', content_type='application/json')

Opportunities.html

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>
            $(document).ready(function(){
                 $('select#selectcompanies').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var source   = optionSelected.text();


                     data = {'selected_company' : source };
                     ajax('/new_opportunity',data,function(result){

                            console.log(result);
                            $("#selectlocations option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectlocations").append('<option>'+ result[i].name +'</option>');
                            };


                         });
                 });
            });
        </script>

<div class="field">
            <label class="label">Client Information:</label>
            <div class="select">
                <select name="selectcompanies" id="selectcompanies">
                    <option value="">Company</option>
                    {% for company in companies %}
                    <option value="" name="selected_company">{{ company.name }}</option>}
                    {% endfor %}
                </select>
            </div>
            <div class="select">
                <select name="selectlocations" id="selectlocations">
                    <option>Location</option>
                    {% for location in locations %}
                    <option value="">{{ location }}</option>
                    {% endfor %}
                </select>
            </div>

1 个答案:

答案 0 :(得分:0)

如果您查看浏览器的控制台(如果不知道是什么,请按F12键),console.log(result);命令记录了什么?我怀疑您没有正确地迭代该结果以填充您的第二选择。

我不确定,但是我认为$("#selectlocations").append('<option>'+ result[i].name +'</option>');行应使用add而不是append并需要一个值和选项。请参见Change the options array of a select list,但可能已过时。

此链接也可能有帮助: https://www.electrictoolbox.com/javascript-add-options-html-select/提出了以下建议,尽管我认为可能有比确定每个循环的长度更好的方法。

var myobject = {
    ValueA : 'Text A',
    ValueB : 'Text B',
    ValueC : 'Text C'
};

var select = document.getElementById("example-select");
for(index in myobject) {
    select.options[select.options.length] = new Option(myobject[index], index);
}