javascript - 将参数从js传递给django
问题描述
我在views.py中有一个函数
def time(request):
date = Registration.objects.filter(date_visit=date_use)
time_list=[]
for a in date:
time_list.append(date.time_visit)
return JsonResponse({'time_list':time_list})
我想从表单中的字段中传递 date_use 参数。
我这样计算字段值
$(document).ready(function() {
$('.pole').change('input', function() {
var val = $(this).val();
});
});
如何将 val 值传递给 date_use?
解决方案
您可以使用data
JSajax
请求中的键在两者中传递参数get
和post
请求。
注意 - 使用 Django 提交表单时,您需要获取csrf token
并将其设置为X-CSRFToken
标题。您可以在此处使用 Django Docs 本身提供的以下代码。
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$('.pole').change('input', function() {
var datetime = $(this).val();
var cookie = getCookie('csrftoken')
$.ajax({
url: '/your-url/',
headers: {'X-CSRFToken': cookie},
type: 'get', // can be 'post' as well or anything else you'd want such as 'put', 'patch', etc'
data: {'datetime': datetime},
success: function(e){
console.log(e)
},
error: function(e){
console.log(e);
}
})
});
视图.py
def time(request):
if request.method == "GET":
date = Registration.objects.filter(date_visit=date_use)
# you can get the value from the JS using the `key` in `data` attribute of `ajax request`
data_from_form = request.GET.get('datetime')
# if you have multiple inputs coming your way for example if there's a list of inputs you're getting you can use
data_from_form = request.GET.getlist('datetime')
time_list=[]
for a in date:
time_list.append(date.time_visit)
return JsonResponse({'time_list':time_list})
注意 - 您可能需要ajax request
在多个页面中使用,并且在每个页面中复制和粘贴该getCookie
功能会适得其反。相反,您可以做的是将此代码粘贴到一个名为的新文件utils.js
中,然后将此文件导入您的base.html
. 请记住,导入定位为utils.js
. 如果您需要将其中的函数使用到另一个脚本中,则需要在下面导入该特定脚本utils.js
base.html
{% load static %}
<html>
<head>
</head>
<body>
<script src="{% static '/js/utils.js' %}" type='text/javascript'></script>
</body>
</html>
推荐阅读
- excel - 未找到数据源名称且未指定默认驱动程序”。无法获取连接“DestinationConnectionOLEDB”
- dart - Flutter - RepaintBoundary 导致 StatefulWidget 的状态重置
- sql-server - 如何使用存储过程从给定的表名中找到数据库的名称?
- json - 如何使用正则表达式搜索键和值并使用 jq 将值替换为新值
- python - 线程 django-main-thread 中的异常
- c# - ConnectionString 用于将 3 个主节点连接到 MySQL
- image - 嵌入式平台上的 Blob 检测,内存受限
- python - 在python中比较日期并在比较中应用条件
- windows - 任务调度程序 - 仅针对特定任务的事件运行
- java - 如何将项目位置适配器发送到片段和片段到活动