Kyl*_*ong 2 python django ajax dynamic-list
我正在制作这个小网络应用程序,它需要 2 个地址,使用谷歌地图计算距离,并根据车辆 mpg 等级计算汽油成本。除了我认为最适合 AJAX 的最后一部分之外,一切都已完成。
我有 3 个列表(年份、品牌、型号),我需要根据汽车的年份和品牌来限制车型列表。选择后,我有一个按钮,一旦点击,将验证它是否是数据库中的有效车辆,并提取车辆的 mpg 等级以对其进行一些基本数学运算。
问题是我真的不知道如何解决这个问题。在过去的几个小时里,我搜索了一些查询,我得到了很多与模型表单和 Django 选择字段相关的东西,如果我不需要,我不想进入。我的想法是只更改innerText/value,然后根据我的django 数据库检查它。
我也从 SO 那里看到了这个答案:
并且对此感到有些困惑。如果我理解正确,AJAX GET 请求将在 javascript 对象中提取数据,就像我作为用户访问该 url 一样。这是否意味着我可以创建另一个 html 模板并将数据库中的每辆车发布到该页面上,我可以从中提取信息并从中创建我的动态列表?
寻找最直接的方法来使用 ajax 动态生成我的列表,并使用我的数据库验证年份、品牌和型号,然后将返回汽车的 mpg。
模型.py:
class Car(models.Model):
year = models.IntegerField(default=0)
make = models.CharField(max_length=60)
model = models.CharField(max_length=60)
mpg = models.IntegerField(default=0)
def __str__(self):
return ("{0} {1} {2}".format(self.year, self.make, self.model))
Run Code Online (Sandbox Code Playgroud)
views.py:(目前只是列出每辆车,无法现场验证车辆)
def index(request):
context_dic = {}
car_list = Car.objects.order_by('make')
car_list_model = Car.objects.order_by('model')
context_dic['car_list'] = car_list
context_dic['years'] = []
context_dic['makes'] = []
context_dic['models'] = []
for year in range(1995, 2016):
context_dic['years'].append(year)
for make in car_list:
if make.make not in context_dic['makes']:
context_dic['makes'].append(make.make)
else:
continue
for model in car_list_model:
if model.model not in context_dic['models']:
context_dic['models'].append(model.model)
else:
continue
return render(request, 'ConverterApp/index.html', context_dic)
Run Code Online (Sandbox Code Playgroud)
html:(品牌和型号为x3)
<div id="specifics">
<div class="dropdown" id="year-dropdown">
<button class="btn btn-default dropdown-toggle" type="button"
id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Year
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
{% for year in years %}
<li><a href="#">{{ year }}</a></li>
{% endfor %}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
javascript:(现在只显示值,但无法与数据库验证)
$('#calculate').on('click', function ()
{
$(this).siblings()[0].textContent = (
document.getElementById("dropdownMenu1").textContent
+ " " + document.getElementById("dropdownMenu2").textContent
+ " " + document.getElementById("dropdownMenu3").textContent
+ " " + document.getElementById("specifics-gas").value
)
});
});
//this part changes the year, make, model to what the user selects //from the list
$('li').on('click', function () {
$(this).parent().siblings()[0].innerHTML = this.innerHTML
//console.log(this.textContent)
});
Run Code Online (Sandbox Code Playgroud)
假设您必须在下拉列表中填充所有品牌名称的静态列表,并且第二个下拉列表应该根据第一个中的选择进行填充。
假设两个简单的 Django 模型定义了品牌和陈列室。
视图.py
class YourView(TemplateView):
template_name = 'template.html'
def get_context_data(self, **kwargs):
brands = Brands.objects.all()
context = super(YourView, self).get_context_data(**kwargs)
context.update({'brands': brands})
return context
def get_showrooms(request, **kwargs):
brand = Brands.objects.get(id=kwargs['brand_id'])
showroom_list = list(brand.showrooms.values('id', 'name'))
return HttpResponse(simplejson.dumps(showroom_list), content_type="application/json"
Run Code Online (Sandbox Code Playgroud)
HTML
<label>Select Brand</label>
<select id="brands" name="brands" class="form-control">
<option value="">Select Brand</option>
{% for brand in brands %}
<option id="{{ brand.id }}" value="{{ brand.id }}">
{{ brand.name }}
</option>
{% endfor %}
</select>
<label>Select Showrroom</label>
<div id="showroom_list">
<select name="showrooms" class="form-control">
</select>
</div
Run Code Online (Sandbox Code Playgroud)
阿贾克斯
$('select[name=brands]').change(function(){
brand_id = $(this).val();
request_url = '/sales/get_showrooms/' + brand_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(index, text){
$('select[name=showrooms]').append(
$('<option></option>').val(index).html(text)
);
};
});
Run Code Online (Sandbox Code Playgroud)
您可以在 request_url 中进行 RESTful 调用。
您可以根据第二个中的选择进一步填充第三个下拉列表,依此类推。此外,您可以访问所选选项并执行更多操作。该选择的插件可以帮助您优化的下拉列表。