使用原生JavaScript向Django传数据时URL渲染404问题排查
问题解决步骤
1. 注入Django URL和CSRF Token到模板
静态JavaScript文件不会经过Django模板引擎处理,所以你写在index.js里的{{ csrf_token }}和{% url %}标签不会被解析,直接当作字符串发送——这就是404错误和CSRF验证失效的根源。
解决方法是在model_upload.html模板中,引入index.js之前,用<script>标签定义全局变量:
<!-- 在 model_upload.html 中,引入 index.js 之前添加 --> <script> // 注入Django生成的目标URL const getSelectionUrl = "{% url 'get_selection' %}"; // 注入CSRF Token const csrfToken = "{{ csrf_token }}"; </script> <script src="{% static 'js/index.js' %}"></script>
2. 修正JavaScript代码错误
修改index.js,使用模板注入的全局变量,同时修正拼写错误(loacation → location,且无需用location.href拼接URL):
let signalSelectButton = document.getElementById("signalSelectButton"); // 使用模板注入的URL const url = getSelectionUrl; signalSelectButton.addEventListener("click", function() { console.log("clicked"); const selectedValue = document.getElementById("signalSelect").value; console.log(selectedValue); fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', // 使用模板注入的CSRF Token 'X-CSRFToken': csrfToken }, body: JSON.stringify({selected_value: selectedValue}) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log(data); document.getElementById('response-message').innerText = data.message; }) .catch(error => {console.error('Error:', error)}); });
3. 修正视图中的JSON解析逻辑
前端发送的是application/json格式的数据,Django的request.POST只能解析表单编码的数据,需要解析request.body获取JSON内容。同时建议去掉@csrf_exempt装饰器(已通过请求头传递有效CSRF Token):
# views.py 中修改 get_selection 视图 import json # 移除 @csrf_exempt 装饰器 def get_selection(request): if request.method == 'POST': # 解析JSON格式的请求体 data = json.loads(request.body) selected_value = data.get('selected_value') return JsonResponse({'message': f'You selected: {selected_value}'}) else: return JsonResponse({'message': ''})
4. 确认URL配置正确性
检查urls.py中的get_selection路径是否无拼写错误:
path("get_selection", views.get_selection, name = "get_selection"),
若项目存在根URL前缀(如gui_app/),确保根URL配置已正确包含该应用的URL,{% url 'get_selection' %}会自动生成带前缀的完整路径。
内容的提问来源于stack exchange,提问作者albas
相关产品推荐
相关产品推荐

