【发布时间】:2021-02-13 13:10:33
【问题描述】:
Getting Error CSRF 验证失败。请求中止。缺少或不正确的令牌。 我是 JQuery 的新手,不确定它是否会导致我的错误。我想我正确地传递了请求。 接受 Cookie,更简单的 JQuery 请求更早地工作。
观看次数
def testcall(request):
text = request.POST['text']
if request.method == 'POST' and request.POST['action'] == 'start_function1':
function1(text)
response = text + "has been successful"
return HttpResponse(response)
if request.method == 'POST' and request.POST['action'] == 'start_function2':
function2(text)
response = text + "has been successful"
return HttpResponse(response)
模板
<html>
<head>
<title>Test Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function($){
$('demo-form').on('submit', function(event){
event.preventDefault();
var text = document.getElementById('text-to-analyze').value;
$.ajax({
url : '{{ 'my-ajax-testsub/' }}',
type : "POST",
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
text: text,
action: 'start_function1'
},
success: function callback(response){
alert(response);
},
});
})})
jQuery(document).ready(function($){
$('demo-form').on('submit', function(event){
event.preventDefault();
var text = document.getElementById('text-to-analyze').value;
$.ajax({
url : '{{ 'my-ajax-testunsub/' }}',
type : "POST",
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
text: text,
action: 'start_function2'
},
success: function callback(response){
alert(response);
},
});
})})
</script>
</head>
<body>
<form name="demo-form" method="POST" action="{% url 'home' %}">
<p>Input field: <input type="text" id="text-to-analyze" value="name@gmail.com"></p><br>
<button class="btn btn-success" name="start_function1">Function</button>
<button class="btn btn-success" name="start_function2">Function</button>
</form>
</body>
</html>
【问题讨论】: