将值从JavaScript传递到Django
我有三种类似的形式:将值从JavaScript传递到Django,javascript,django,Javascript,Django,我有三种类似的形式: <form id = "myForm" style="list-style-type: none;display: none;" class="form_class"> {% csrf_token %} item1: <input type="text" name
<form id = "myForm" style="list-style-type: none;display: none;" class="form_class">
{% csrf_token %}
item1:
<input type="text" name="item1" style="width:10%;height:5%">
<br>
item2:
<input type="text" name="item2" style="width:10%;height: 5%">
<br>
item2:
<input type="text" name="item2" style="width:10%;height: 5%">
<br>
item2:
<input type="text" name="item2" style="width:10%;height: 5%">
<br>
item2:
<input type="text" name="item2" style="width:10%;height: 5%">
<br><br>
<input id="close_form" type="reset" value="reset">
</form>
{%csrf_令牌%}
项目1:
项目2:
项目2:
项目2:
项目2:
下面是我用来单击按钮的代码,这样它将转到javascript方法:
<form method="post">
{% csrf_token %}
<input class="bg-yellow text-white" value="RUN" name="runModel" type="submit"
onclick="sendValuesToBack()">
</form>
{%csrf_令牌%}
在JavaScript方法中,我得到了所有三个表单的值。我想把它们发送到Django框架来执行几个操作。如何将这些数据从JavaScript发送到Django?您可以在模板中使用JQuery Ajax并在views.py中创建一个“API视图”,这基本上只是一个常规视图,在检查验证请求是否为Ajax后返回一个
JSONResponse
。作为“API”选项的一个示例,使用JQuery:
在您的URL.py中:
...
path('/api/post_form/', post_form_api, name="post_form_api"),
...
对于views.py中的POST方法:
from django.http import JsonResponse
def post_form_api(request):
data = {}
if request.method == "POST":
form = MyDjangoForm(request.POST)
# do something with the form data
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
def post_form_api(request):
data = {}
if request.method == "POST":
form_name = request.POST.get('form_name', None) #the name of the hidden field identifying the form
if form_name is not None:
if form_name == "MyDjangoForm":
form = MyDjangoForm(request.POST)
# do something with the form data
...
elif form_name == "MyOtherForm":
form = MyOtherForm(request.POST)
# do something with the form data
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
在模板中:
<script type="text/javascript">
$("#myFormSubmitButton").click(function(){
var form_data = $("#formID").serialize();
$.ajax({ url: '{% url 'post_form_api' %}',
type: "POST",
dataType: "json",
data: form_data,
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
如果您同时从模板中的所有三个表单获取数据,则在使用JQuery Ajax发送所有数据后,可以在views.py中执行类似操作,如上所述:
def post_form_api(request):
data = {}
if request.method == "POST":
item_1 = request.POST.get('item_1', None)
item_2 = request.POST.get('item_2', None)
item_3 = request.POST.get('item_3', None)
...
# do something with the collected form data here
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
当您通过POST发送数据时,不要忘记传递CSRF令牌,如上面的示例所示(它应该是序列化形式的数据)。这假设您在页面上有一个表单,您可以从中获取表单,否则您可以使用类似以下的方式获取表单:
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;
}
var csrftoken = getCookie('csrftoken');
现在,在不知道更多的情况下,这基本上只是伪代码(加上我只是在脑海中写下了这个,所以可能会有错误)。这还取决于您使用的视图类型,以及是否要使用Django REST框架(上面的示例是针对常规视图,而不是基于类的视图,不需要Django REST框架)
如果您发布更多详细信息,我可以更新我的答案,但我认为这应该可以让您开始。您可以在模板中使用JQuery Ajax并在视图中创建“API视图”。py这基本上只是一个常规视图,在检查验证请求是否为Ajax后返回
JSONResponse
。作为“API”选项的一个示例,使用JQuery:
在您的URL.py中:
...
path('/api/post_form/', post_form_api, name="post_form_api"),
...
对于views.py中的POST方法:
from django.http import JsonResponse
def post_form_api(request):
data = {}
if request.method == "POST":
form = MyDjangoForm(request.POST)
# do something with the form data
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
def post_form_api(request):
data = {}
if request.method == "POST":
form_name = request.POST.get('form_name', None) #the name of the hidden field identifying the form
if form_name is not None:
if form_name == "MyDjangoForm":
form = MyDjangoForm(request.POST)
# do something with the form data
...
elif form_name == "MyOtherForm":
form = MyOtherForm(request.POST)
# do something with the form data
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
在模板中:
<script type="text/javascript">
$("#myFormSubmitButton").click(function(){
var form_data = $("#formID").serialize();
$.ajax({ url: '{% url 'post_form_api' %}',
type: "POST",
dataType: "json",
data: form_data,
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
如果您同时从模板中的所有三个表单获取数据,则在使用JQuery Ajax发送所有数据后,可以在views.py中执行类似操作,如上所述:
def post_form_api(request):
data = {}
if request.method == "POST":
item_1 = request.POST.get('item_1', None)
item_2 = request.POST.get('item_2', None)
item_3 = request.POST.get('item_3', None)
...
# do something with the collected form data here
...
if successful:
data['result'] = True
data['message'] = "Form data saved"
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
当您通过POST发送数据时,不要忘记传递CSRF令牌,如上面的示例所示(它应该是序列化形式的数据)。这假设您在页面上有一个表单,您可以从中获取表单,否则您可以使用类似以下的方式获取表单:
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;
}
var csrftoken = getCookie('csrftoken');
现在,在不知道更多的情况下,这基本上只是伪代码(加上我只是在脑海中写下了这个,所以可能会有错误)。这还取决于您使用的视图类型,以及是否要使用Django REST框架(上面的示例是针对常规视图,而不是基于类的视图,不需要Django REST框架)
如果你发布更多细节,我可以更新我的答案,但我认为这应该让你开始