使用csrf令牌在ajax视图上出现django 403错误

时间:2014-06-30 18:38:53

标签: ajax django csrf

我试图找出如何使用django的ajax,并且我一直遇到403错误。 (就我所知,这意味着我的CSRF令牌出错了。 但我无法弄清楚我做错了什么。

网址:

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^person/(?P<person_id>\d+)/$', views.person, name="person"),
    url(r'^search/$', views.search, name="search"),
    url(r'^search_person/$', views.search_person, name="search person"),
)

我的观点:

def search(request):
    args = {}
    args.update(csrf(request))
    return render(request, "search.html", args)

def search_person(request):
    if request.POST:
        search_text = request.POST['search_text']
    else:
        search_text = ""

    persons = Person.objects.filter(name__contains=search_text)
    return render_to_response("ajax_search.html", {"persons": persons})

我的模板: (search.html)

{% block js %}
    <script type="text/javascript" src="{% static 'assets/js/ajax_search.js' %}"></script>
{% endblock %}

{% block content %}
Search:<br>
{% csrf_token %}
<input type="text" id="search" name="search" />
<ul id="search-results">

</ul>
{% endblock %}

(ajax_search.html)

{% if persons.count > 0 %}
    {% for person in persons %}
    <li><a href="{% url 'person' person.id %}">{{ person.full_name }}</a></li>
    {% endfor %}

{% else %}
<li>No Results</li>

{% endif %}

最后我的jquery

$(function(){
    $('#search').keyup(function(){
        $.ajax({
            csrfmiddlewaretoken: $('input[csrfmiddlewaretoken]').val(), 
            type: "POST", 
            url: "/search_person/", 
            data: {
                'search_text': $('#search').val()
            },
            succes: searchSucces,
            dataType: "html"
        });
    });
});

function searchSucces(data, textStatus, jqXHR){
    $('#search-results').html(data);
}

我的csrf令牌出了什么问题?

2 个答案:

答案 0 :(得分:1)

我会给你发一个用Javascript做的POST请求,包括CSRF令牌,也许它可以帮到你:

function post_to_url(path, params) {
    method = "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    //We add the CSRF token
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "csrfmiddlewaretoken");
    hiddenField.setAttribute("value", getCookie('csrftoken'));
    form.appendChild(hiddenField);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "type_recherche");
    hiddenField.setAttribute("value", "loc");

    form.appendChild(hiddenField);

    document.body.appendChild(form);
    form.submit();
}

答案 1 :(得分:0)

想出怎么做,所以不妨发布答案。

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(){
    $('#search').keyup(function(){
        $.ajax({type: "POST", url: "/search_person/", 
            data: {
                'search_text': $('#search').val(),
                csrfmiddlewaretoken: csrftoken
            },
            success: searchSuccess,
            dataType: "html"
        });     
    });
});

function searchSuccess(data, textStatus, jqXHR){
    $('#search_results').html(data);
}