Django jQuery 发布请求 [英] Django jQuery post request

查看:17
本文介绍了Django jQuery 发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在 views.py 中:

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...

我得到:[05/Oct/2012 12:03:58] "POST/something/HTTP/1.1" 403 2294

我想通过 jQuery 将此数据(姓名和年龄)发送到SomeView"中的此 post 函数.这与加载的模板是相同的视图,只是请求类型不同.在 get() 模板加载时,应调用 post() 函数.是否可以?我检查了其他问题并得到了这个解决方案.它应该可以工作.我做错了什么?

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?

推荐答案

问题的答案是:你做错了什么:不多!

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

如果传入的 POST 请求未通过 Csrf 检查,Django 将返回 403 响应(禁止).您可以通过 jQuery 的 ajaxSetup 执行此操作,代码片段位于 此处

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

这对 GET 请求有效的原因很简单,因为 csrf 中间件没有检查 GET 请求.

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

由于您在这里构建表单,因此需要考虑的另一件事是使用基于类的表单.他们为您处理 get/post 和参数验证.非常整洁.特别是当您制作用于编辑/创建/删除模型实例的表单时,在这种情况下,您可以使用 ModelForms 和 CreateViews.很整洁.

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.

这篇关于Django jQuery 发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆