问题
Using jquery1.7.1 and django1.3 ,I was trying to make a post request through ajax,in some tutorial code I found on web
$(document).ready(function(){
$("#create").click(create_note);
});
var create_note = function() {
var title = $("#title").val()
var slug = $("#slug").val()
if (title != "" && slug != "") {
var data = { title:title, slug:slug };
console.log('title='+title);
console.log('slug='+slug);
var args = { type:"POST", url:"/create/", data:data, complete:done };
$.ajax(args);
}
else {
// display failure
}
return false;
};
The url "/create/" is mapped to django view
(r'^create/$','notes.views.create_note'),
def create_note(request):
error_msg = u"No POST data sent."
if request.method == "POST":
post = request.POST.copy()
if post.has_key('slug') and post.has_key('title'):
slug = post['slug']
if Note.objects.filter(slug=slug).count() > 0:
error_msg = u"Slug already in use."
else:
title = post['title']
new_note = Note.objects.create(title=title,slug=slug)
return HttpResponseRedirect(new_note.get_absolute_url())
else:
error_msg = u"Insufficient POST data (need 'slug' and 'title'!)"
return HttpResponseServerError(error_msg)
When I click the submit button,which triggers the javascript function create_note
,I get a 403 error. Must be the csrf problem..
I tried to solve this by modifying the ready function
$(document).ready(function(){
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
$("#create").click(create_note);
});
but it didn't work..I still get 403 error
So,I tried to modify the data in ajax
call
var create_note = function() {
var data = { title:title, slug:slug ,csrfmiddlewaretoken: '{{ csrf_token }}'};
...
var args = { type:"POST", url:"/create/", data:data, complete:done };
$.ajax(args);
};
Still it causes 403 error..
Please tell me what should be done to correct this..I saw the
django doc about this,but I am confused how to make use of that.Should I copy the entire jQuery(document).ajaxSend(...
code in to my javascript file..I am really confused here..
回答1:
You need to (as the document you linked to suggests) copy that entire ajaxSend
method ...
You dont need to modify it in any way - it is a complete solution - the ajaxSend
method is actually an event handler for the ajaxSend
event. Its triggered when you use the .ajax
method in jQuery. See the ajaxSend docs here
The method linked in the above document appends the correct X-CSRFToken
header to your AJAX request. You can then use your first method for sending the AJAX request.
来源:https://stackoverflow.com/questions/10562494/csrf-with-ajax-and-django-post