问题
I am trying to figure out how to use ajax with django, and i keep running into the 403 error. (which means as far as i know, that something with my CSRF token goes wrong. But i cant figure out what i do wrong.
urls:
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"),
)
My views:
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})
My templates: (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 %}
and finaly my 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);
}
What am i doing wrong with my csrf token?
回答1:
I'll post you a POST request made in Javascript including the CRSF token, maybe it can help you :
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();
}
回答2:
Figured out how to do it, so might as well post the awnser.
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);
}
来源:https://stackoverflow.com/questions/24496751/django-403-error-on-ajax-view-with-csrf-token