如何在 Django 中使用 Ajax JQuery 调用下拉列表 html 选择
Posted
技术标签:
【中文标题】如何在 Django 中使用 Ajax JQuery 调用下拉列表 html 选择【英文标题】:How to call a dropdown list html select with Ajax JQuery in Django 【发布时间】:2021-11-15 00:58:29 【问题描述】:我想在第一个选择下拉列表中选择一个选项,并且根据所选选项,ajax 应该加载第二个选择下拉列表,该怎么做?
这是我的代码:
型号:
class MaintenanceEquipment(models.Model):
equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True)
line_nm = models.CharField(max_length=20, blank=True, null = True)
sequence = models.CharField(max_length=30, blank=True, null = True)
equip_model = models.CharField(max_length=30, blank=True, null = True)
def __str__(self):
return self.equip_id
观看次数:
from django.shortcuts import render
from maintenance.models import MaintenanceEquipment
def maintenanceIssueView(request):
equipment_list = MaintenanceEquipment.objects.all()
context = 'equipment_list':equipment_list
return render(request, 'maintenance/maintenanceIssue.html', context)
def load_equipment(request):
if request.method == 'GET':
line = request.GET.get('line_nm')
equipment = MaintenanceEquipment.objects.filter(line_nm=line)
context = 'equipment': equipment
return render(request, 'maintenance/maintenanceIssue.html', context)
网址:
urlpatterns = [
path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"),
path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"),
]
maintenanceIssue.html:
<form method="POST" id="maintenanceForm" data-equipment-url="% url 'ajax_load_equipment' %" novalidate>
% csrf_token %
<div style="text-align:left;" class="container-fluid">
<div style="text-align:left;" class="form-row">
<div class="form-group col-md-6">
<label for="line_nm" style="font-size:medium;">Line</label>
<select class="form-control" id="line_nm" name="line_nm" >
% for instance in equipment_list %
<option id=" instance.line_nm " value=" instance.line_nm "> instance.line_nm </option>
% endfor %
</select>
</div>
<div class="form-group col-md-6">
<label for="sequence" style="font-size:medium;">Machine</label>
<select class="form-control" id="sequence" name="sequence">
% for instance in equipment %
<option value=" instance.sequence "> instance.sequence </option>
% endfor %
</select>
</div>
</div>
</div>
</form>
<script>
$("#line_nm").change(function ()
var url = $("#maintenanceForm").attr("data-equipment-url");
var line_nm = $(this).val();
$.ajax(
url: url,
data:
'line_nm': line_nm
,
success: function (data)
$("#sequence").html(data);
console.log(data);
);
);
</script>
数据通过GET正确发送到视图,这是我的终端:
[2021 年 9 月 21 日 08:34:43] “获取 /maintenance/ajax/load_equipment/?line_nm=SMD-16 HTTP/1.1" 200 18644
这是 console.log 的正确结果:
<select class="form-control" id="sequence" name="sequence">
<option name = "sequence" value="470">LOADER1</option>
<option name = "sequence" value="471">PRINTER1</option>
<option name = "sequence" value="472">PRINTER2</option>
<option name = "sequence" value="473">CARRIER JIG UNLOADER </option>
<option name = "sequence" value="474">P-AOI</option>
<option name = "sequence" value="475">P-AOI NG BUFFER</option>
<option name = "sequence" value="476">SHUTTLE1</option>
<option name = "sequence" value="477">MOUNTER1</option>
<option name = "sequence" value="478">MOUNTER2</option>
<option name = "sequence" value="479">MOUNTER3</option>
<option name = "sequence" value="480">MOUNTER4</option>
</select>
但是,在我的 html 中选择“序列”显示为空,我尝试了很多东西,但暂时没有成功。
【问题讨论】:
$("#sequence").html(data)
设置给定元素的innerHTML,但在您的情况下,变量data
以<select>
开头,因此您将<select>
设置在另一个<select>
中,而不仅仅是@987654332 @ 项目。这可能是问题所在。
我上面显示的“数据”是仅在console.log(数据)中显示的预期结果,但在html中选择值来自$(“#sequence”).html (数据)是空的,我说的对吗?
嗨,你可以试试这样吗:$("#sequence").replaceWith(data);
你好 Swati,这段代码正在加载序列,但它在第一个表单中创建了另一个表单,有什么技巧可以避免吗?
如果我正确理解您的帖子,您正在寻找依赖下拉菜单。看看这个帖子simpleisbetterthancomplex.com/tutorial/2018/01/29/…
【参考方案1】:
这是一般模式:
template.html
<!-- first select populated with context variables -->
<select id='first-select'>
% for instance in instances %
<option value=" instance.id">
instance.text
</option>
% endfor %
</select>
<!-- second select populated with response from ajax -->
<select id='second-select'></select>
script.js
$('#first-select').change(function()
// send ajax request when the first select is changed:
$.ajax(
url : 'the-url',
type : 'POST',
data :
instanceID : $(this).val()
,
success : function(response)
// this function executes on receiving a successful response from the backend:
var secondSelect = $('#second-select');
secondSelect.empty();
// iterate over the instances in the response and add them to the second select
for (var instance in response.instances)
secondSelect.append($('<option>',
value : instance.id,
text : instance.text
));
);
views.py
def render_template(request):
""" this method renders the template with context variables """
# set context variables:
context =
"instances" : FirstModel.objects.all()
return render(request, 'template.html', context=context)
def get_instances(request):
""" this method returns json-friendly instances for the second select """
# unpack request:
instance_id = request.POST.get('instanceID')
# get instance:
instance = FirstModel.objects.get(id=instance_id)
# get instances
other_instances = SecondModel.objects.filter(first_model = instance)
# serialize data:
...
return JsonResponse(
"status_code" : 200,
"instances" : other_instances
)
【讨论】:
以上是关于如何在 Django 中使用 Ajax JQuery 调用下拉列表 html 选择的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Django 中使用 jQuery/Ajax 发布?