Django / AJAX / JQuery - 无法收到POST响应

时间:2013-02-27 18:45:47

标签: django jquery

好的,首先,我是一个JQuery / AJAX noob,但我可以设法绕过大部分时间。

这是问题所在。

出于某种原因,每次我使用POST作为AJAX类型我都没有得到响应,但是当我使用GET时,我确实得到了响应。

为什么会发生这种情况,我该如何解决呢?

HTML

<form action="/trivia/ajax_test/" method="post" onsubmit="return ajaxTest()">
{% csrf_token %}
<button type="submit">AJAX</button>
</form>

的JQuery / AJAX

function ajaxTest() { 
    $.ajax({
        type: 'POST', // Works with 'GET', but failing with 'POST'
        url: '/trivia/ajax_test/',
        data: {some_text: 'The test is working'},
        success: function(result){alert(result);} 
    });

    return false;
}

URLS

(r'^trivia/ajax_test/$', 'findadownload.trivia.views.ajax_test'),

视图

def ajax_test(request):
    if request.is_ajax():
        return HttpResponse("Success")

    else:
        result = "You went to the url directly"

    return HttpResponse(result)

1 个答案:

答案 0 :(得分:2)

这是因为Django内置了CSRF protection

在您的Ajax通话之前将此添加到您的Javascript或POST视图的disable CSRF protection

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;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});