如何在Jquery中执行Post请求并传递Django CSRF令牌?

时间:2011-11-19 12:40:54

标签: jquery ajax django django-views

我正在尝试在Jquery中向Django服务器实现POST请求。问题是我需要传递CSRF令牌。所以我在请求代码之前在我的JS文件中复制this code。但是,没有任何反应。 Firebug控制台显示错误500(内部服务器错误),如果我将Post请求更改为get请求,它会执​​行请求。

JS档案

复制的代码

$(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'));
}

});

我的代码

 $(document).ready(function(){
      $.post('/favorites/delete_favorite/' + data_info[0] + '/' + data_info[1], function(data){
           alert(data);
      });

View.py

def delete_favorite(request, content_type=None, object_id=None):

    if request.method == 'POST':
         message = "Hello POST"
    else:        
         message = "Hello"

    return HttpResponse(message)
 });

解决方案 我发送网址时出错,它错过了斜线,所以正确的解决方案是:

(文档)$。就绪(函数(){       $ .post('/ favorites / delete_favorite /'+ data_info [0] +'/'+ data_info [1] +'/',function(data){            警报(数据);       });

我不会删除此帖子,因为有人可能需要它。

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的,你的views.py文件看起来很好。

$.ajax({
    url:"/favorites/delete_favorite/' + data_info[0] + '/' + data_info[1]",
    type: "POST",
    data: {values:['1','2'], csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()},
    success:function(response){
        alert("success: " + response);
    },
    error:function (xhr, textStatus, thrownError){
        alert("xhr status: " + xhr.statusText);
    },

});

或者,您可以在视图功能上使用@csrf_exempt

@csrf_exempt
def delete_favorite(request, content_type=None, object_id=None):

    if request.method == 'POST':
        message = "Hello POST"
    else:        
        message = "Hello"

    return HttpResponse(message)
});

答案 1 :(得分:0)

如果您使用的是django 1.3,则可以使用javascript这样的功能

($)(function(){

$.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'));
        }
    }
});

});

在这种情况下,您可以像csrftoken一样通过     {csrftoken:{{csrf_token}}} 以及您的post data

请注意,如果您使用

,这将很有效
def function(request):
    .....
    ctx = RequestContext(request, {})
    return render_to_response(template, ctx)

如果您使用django 1.4,则需要将csrftoken替换为csrfmiddlewaretoken