如何获取脚本数据填充Django ChoiceField?AJAX响应无数据问题
问题解决:Django视图返回JSON但AJAX无法获取数据并填充ChoiceField
核心问题
你的代码中AJAX请求没有解析JSON响应,仅返回了原始Response对象,无法拿到实际数据;另外用户输入的特殊字符可能导致URL无效,也需要处理。
分步修复
1. 修正JavaScript的Fetch逻辑
修改courses.js,添加JSON解析、URL编码和ChoiceField填充逻辑:
'use strict'; const courseNameBtn = document.getElementById('button-addon2'); // 替换成你表单中ChoiceField的实际ID const courseSelect = document.getElementById('id_course_choice'); const getCountryData = function () { const courseName = document.getElementById('id_courseLookup').value; // 编码特殊字符,避免空格/特殊符号导致URL错误 const encodedCourseName = encodeURIComponent(courseName); // 使用相对路径,避免硬编码域名更灵活 fetch(`/golf_courses/lookup/${encodedCourseName}/`) .then(response => { if (!response.ok) throw new Error(`请求错误:${response.status}`); return response.json(); // 解析JSON响应,拿到实际数据 }) .then(data => { // 清空现有选项 courseSelect.innerHTML = ''; // 添加默认提示项 const defaultOpt = document.createElement('option'); defaultOpt.value = ''; defaultOpt.textContent = '请选择匹配的球场'; courseSelect.appendChild(defaultOpt); // 遍历数据生成选项 Object.entries(data).forEach(([key, name]) => { const option = document.createElement('option'); option.value = key; // 可根据需求替换为实际球场ID(如果有的话) option.textContent = name; courseSelect.appendChild(option); }); }) .catch(err => console.error('数据获取失败:', err)); }; courseNameBtn.addEventListener('click', getCountryData);
2. 优化Django URL配置
去掉URL路径中的正则前缀r(path语法不需要):
# urls.py app_name='golf_courses' urlpatterns = [ path('add/', Golf_CourseCreateView.as_view(), name='add'), path('lookup/<str:courseName>/', lookupCourses, name='lookup'), ]
3. 确保视图返回有效JSON
你的lookupCourses视图逻辑没问题,course_query返回的字典可直接通过JsonResponse序列化:
# views.py def lookupCourses(request, courseName): course_result = course_query(courseName) return JsonResponse(course_result)
关键注意事项
- URL编码:用户输入的球场名称可能包含空格、特殊字符,必须用
encodeURIComponent编码,否则会导致请求路径无效。 - 错误处理:添加
catch块和响应状态检查,方便调试请求失败的原因(比如404、500错误)。 - 相对路径:使用相对路径
/golf_courses/lookup/...替代硬编码的http://127.0.0.1:8000,适配不同部署环境。
内容的提问来源于stack exchange,提问作者egkennedy93
相关产品推荐
相关产品推荐

