错误:“CSRF验证失败。请求已中止。“当Django使用jquery ajax时 [英] error: "CSRF verification failed. Request aborted." when using jquery ajax with Django
本文介绍了错误:“CSRF验证失败。请求已中止。“当Django使用jquery ajax时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在模板中:
<script type="text/javascript">
$.ajax({
type:"POST",
url:"{% url DrHub.views.ajxTest %}",
data: {
'start': $('#id_startTime').val(),
'end': $('#id_endTime').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(data){
alert(data);
}
});
</script>
.
.
.
<form method='POST' action=".">
{% csrf_token %}
<input type="text id="id_startTime" />
<input type="text id="id_endTime" />
<input type="submit" value="send" />
</form>
在视图中:
def ajxTest(request):
if request.is_ajax():
if request.method == 'POST':
return HttpResponse(json.dumps({'message' : 'awesome'},ensure_ascii=False), mimetype='application/javascript')
在settings.py中:
in settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
提交表单时我有这个错误: CSRF验证失败。请求中止。
when submitting form I have this error:CSRF verification failed. Request aborted.
我搜索了很多,但没有一个建议的解决方案适用于我!
I searched alot but none of suggested solutions worked for me!
如下: Django CSRF检查失败,使用Ajax POST请求
我重新使用了这个内容的js文件:
I refreenced to a js file with this content:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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 = jQuery.trim(cookies[i]);
// 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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
但这样也没有起作用。
我看到一个解决方案,说使用ajaxSetup而不是ajaxSend发布数据,我该怎么做?
And I saw a solution that say use ajaxSetup instead of ajaxSend to post data,how can I do this?
推荐答案
这是一个关于这个内容的js文件的引用是我的解决方案:
having this a refrence to a js file with this content was my solution:
jQuery(document).ajaxSend(function(event, xhr, settings) {
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 = jQuery.trim(cookies[i]);
// 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;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
这篇关于错误:“CSRF验证失败。请求已中止。“当Django使用jquery ajax时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文