从 Django 中的 JsonResponse 中提取字段值并将其传递给 Ajax Jquery
Posted
技术标签:
【中文标题】从 Django 中的 JsonResponse 中提取字段值并将其传递给 Ajax Jquery【英文标题】:Extracting a field value from JsonResponse in Django and pass it to Ajax Jquery 【发布时间】:2021-11-19 14:53:33 【问题描述】:我正在 Django 中使用 ajax 和 Jquery 创建一个下拉列表选择 预期的行为是当我选择第一个选择时,ajax 将填充第二个 这是我暂时拥有的:
models.py
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
views.py:
def maintenanceIssueView(request):
equipment_list = MaintenanceEquipment.objects.all()
context = 'equipment_list':equipment_list
return render(request, 'maintenance/maintenanceIssue.html', context)
def load_equipment(request):
from django.core import serializers
if request.method == 'GET':
line_nm = request.GET.get('line_nm')
equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm)
instances = serializers.serialize('json', equipment)
print(instances)
return HttpResponse(instances, content_type='application/json')
urls.py:
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"></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 (response)
// this function executes on receiving a successful response from the backend:
var secondSelect = $('#sequence');
secondSelect.empty();
for (var instance in response.instances)
secondSelect.append($('<option>',
value : instance.sequence,
text : instance.sequence
));
);
);
</script>
问题是: 当我在终端中打印视图的输出时,我有:
["model": "maintenance.maintenanceequipment", "pk": 4,
"fields":
"equip_id": "Q230-095504-003", "mfg_part_code": "P12122", "line_nm":
"PBA-02", "sequence": "LOADER", "equip_model": "FML-400BAI-HE-SV",
"model": "maintenance.maintenanceequipment", "pk": 5,
"fields":
"equip_id": "Q230-108839-001", "mfg_part_code": "P12122", "line_nm":
"PBA-02", "sequence": "C-MOUNTER1", "equip_model": "MAI-H8"]
如何在我的 ajax 中恢复它以填充第二个选择? 我需要的唯一数据是 "fields": sequence
预期值:装载机、C-MOUNTER1
当前出现在 select 中的值是:0, 1, 2, 3, 4, 5, 6, 7 ....也许是一个字符串计数
如果有人可以提供帮助,我将不胜感激
【问题讨论】:
【参考方案1】:您需要解析从服务器获得的 JSON 响应,然后遍历 JSON Array 并使用 response["instances"][i] 获取序列值[“字段”][“序列”] .
演示代码:
//this is for demo ....
var response =
"instances": [
"model": "maintenance.maintenanceequipment",
"pk": 4,
"fields":
"equip_id": "Q230-095504-003",
"mfg_part_code": "P12122",
"line_nm": "PBA-02",
"sequence": "LOADER",
"equip_model": "FML-400BAI-HE-SV"
,
"model": "maintenance.maintenanceequipment",
"pk": 5,
"fields":
"equip_id": "Q230-108839-001",
"mfg_part_code": "P12122",
"line_nm": "PBA-02",
"sequence": "C-MOUNTER1",
"equip_model": "MAI-H8"
]
/*$("#line_nm").change(function ()
var url = $("#maintenanceForm").attr("data-equipment-url");
var line_nm = $(this).val();
$.ajax(
url: url,
data:
'line_nm': line_nm
,
dataType :'json', //add this....///
success: function (response) */
var secondSelect = $('#sequence');
secondSelect.empty();
//loop thorugh json response //is its json object > json array use : response.instances
for (var i = 0; i < response.instances.length; i++)
secondSelect.append($('<option>',
value: response["instances"][i]["fields"]["sequence"], //get the sequence
text: response["instances"][i]["fields"]["sequence"]
));
/*
);
);*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select class="form-control" id="sequence" name="sequence"></select>
【讨论】:
谢谢斯瓦蒂,它确实解决了我的问题,在此之后我只需要改变我的观点,我正在使用 JsonResponse() 并将其更改为 HttpResponse() 很高兴我能帮上忙 :)【参考方案2】:如果你只需要序列字段,你可以用Django直接获取这个字段
equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm)
equipment_sequences = [e.sequence for e in equipment]
【讨论】:
以上是关于从 Django 中的 JsonResponse 中提取字段值并将其传递给 Ajax Jquery的主要内容,如果未能解决你的问题,请参考以下文章
Django - JsonResponse 中的服务器代码响应