错误:" CSRF验证失败。请求中止与QUOT。使用与Django的jQuery的Ajax时 [英] error: "CSRF verification failed. Request aborted." when using jquery ajax with Django

查看:1514
本文介绍了错误:" CSRF验证失败。请求中止与QUOT。使用与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验证失败。请求中止。

我搜索了很多,但没有提出解决方案,为我工作!

I searched alot but none of suggested solutions worked for me!

这样的:<一href="http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request">Django CSRF检查与一个Ajax POST请求失败

和:阿贾克斯邮政Django框架

我refreenced到一个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'));
         }
     } 
});

但这并没有工作,太!

but this didn't work,too!

和我看到了一个解决方案,说使用ajaxSetup代替ajaxSend发布的数据,我该怎么办呢?

And I saw a solution that say use ajaxSetup instead of ajaxSend to post data,how can I do this?

推荐答案

有这样的refrence与此内容的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'));
    }
});

这篇关于错误:&QUOT; CSRF验证失败。请求中止与QUOT。使用与Django的jQuery的Ajax时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆