Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - Django jQuery post request

$.ajax({
    url:'/',
    type: "POST",
    data: {name: 'name', age: 'age'},
    success:function(response){},
    complete:function(){},
    error:function (xhr, textStatus, thrownError){}
});

And in views.py:

class SomeView(generic_views.TemplateView):
    template_name = 'something.html'

    def get(self, request, *args, **kwargs):
        ...something...
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        name = request.POST['name']
        age = request.POST['age']
        ...something...

And I get: [05/Oct/2012 12:03:58] "POST /something/ HTTP/1.1" 403 2294

I'd like to send this data(name and age) via jQuery to this post function in "SomeView". This is the same view as the loaded template, just the request type is different. On get() the template loads and on post, the post() function should be called. Is it possible? I've checked other questions and got this solution. It was supposed to be working. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer to your question what you are doing wrong, is: not much!

Django returns a 403 response (Forbidden) if an incoming POST request fails Csrf checks. You can do this through jQuery's ajaxSetup, code snippets are found here

The reason that this DOES work on a GET request, is simply that GET requests are not checked by the csrf middleware.

As it seems you are building a form here, another thing to consider is using class based forms. They handle get/post and also parameter validation for you. Very neat. Especially when you are making forms to edit/create/delete model instances, in which case you can embrace the power of ModelForms and CreateViews. Very neat.

It might take some time to get the hang of those generic class based views. But it's very well worth it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...