javascript Django jQuery 发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:01:18  来源:igfitidea点击:

Django jQuery post request

javascriptjquerydjangopostrequest

提问by premik91

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

And in views.py:

在 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

我得到:[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?

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

回答by A.J.Rouvoet

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

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

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

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

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 ModelFormsand CreateViews. Very neat.

就像您在这里构建表单一样,要考虑的另一件事是使用基于类的表单。他们为您处理 get/post 和参数验证。非常整洁。尤其是当您制作用于编辑/创建/删除模型实例的表单时,在这种情况下,您可以使用ModelForms和 CreateViews的强大功能。非常整洁。

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

掌握那些基于类的通用视图可能需要一些时间。但这是非常值得的。

回答by Hoff

You need to include a CSRF (cross-site request forgery)token in your ajax call. This is well documented here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

您需要在 ajax 调用中包含CSRF(跨站点请求伪造)令牌。这在此处有详细记录:https: //docs.djangoproject.com/en/dev/ref/contrib/csrf/

or, if you want to use a quick fix, use the @csrf_exemptdecorator for your view:

或者,如果您想使用快速修复,请@csrf_exempt为您的视图使用装饰器:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
   ...

回答by JxAxMxIxN

Within a Django template you can add this...

在 Django 模板中,您可以添加这个...

{% csrf_token %}

Which will output something like this to your page html...

它将向您的页面 html 输出类似的内容...

<input type="hidden" name="csrfmiddlewaretoken" value="ckhUdNOTj88A...hfTnREALlks2kz">

Then using Javascript you can simply find this input and get its value - something like this non jQuery example...

然后使用 Javascript 你可以简单地找到这个输入并获取它的值 - 就像这个非 jQuery 示例......

var el = document.getElementsByName("csrfmiddlewaretoken");
csrf_value = el[0].getAttribute("value");

Lastly add the csrf_value to your jQuery AJAX post form data line like so...

最后将 csrf_value 添加到您的 jQuery AJAX 发布表单数据行中,如下所示...

data: {name: 'name', age: 'age', csrfmiddlewaretoken: csrf_value},

Here's a working jsFiddle concept: https://jsfiddle.net/vdx1Lfpc/18/

这是一个有效的 jsFiddle 概念:https://jsfiddle.net/vdx1Lfpc/18/

回答by Sevenearths

I read on another post that you can do something like this:

我在另一篇文章中读到你可以做这样的事情:

$.ajax({
    method: "POST",
    url: "{% url 'some_route' %}",
    headers: {'X-CSRFToken': '{{ csrf_token }}'},
    contentType: "application/json",
    dataType: 'json',
    data: {name:$('#id_name').val()}
})
.fail(function(message) {
    alert('error');
})
.done(function(data) {
    alert(data);
});