【发布时间】:2019-10-20 09:50:48
【问题描述】:
我想创建相关的下拉菜单,但我不确定如何最好地实施该解决方案。根据在第一个下拉菜单中选择的值,我想在查询中使用该值填充后续下拉菜单。尽管我已经完成了工作,但在第一个下拉菜单中选择了一个值后,我没有返回任何数据。如果我可以提供任何其他信息来更好地说明我的问题,请告诉我。
模型.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>
【问题讨论】:
-
手动浏览到
/new_opportunity时会发生什么?cwObj是什么?我怀疑你遇到了一些错误。使用 Chrome 的开发者工具查看您收到的回复(或使用类似工具选择您最喜欢的浏览器)。 -
@AMG 当我导航到“/opportunities/new_opportunity”时,我看到了 TypeError: “'NoneType' object is not subscriptable” on this line “string = str(source[1:-1 ])?”。最后,cwObj 是一个由我的 RESTful API 调用返回到数据库的 JSON 响应制成的对象。谢谢!
-
尝试
/new_opportunity?selected_company=1或您公司模型中的任何有效ID。 -
@AMG 我用我的 JSON 响应解决了我的问题,现在我在“/opportunities/new_opportunity”看到一个特定“selected_company”的填充下拉菜单。但是,当我在第一个下拉列表中选择一家公司时,不会根据选择填充第二个下拉列表。有什么想法吗?谢谢!