简体   繁体   English

如何在 Django 中处理 AJAX POST 请求

[英]How to handle AJAX POST request in Django

I have a sort of twitter like button function in my app such that, when the button is clicked, it triggers an AJAX call and performs the action specified in the views.我的应用程序中有一种 twitter 之类的按钮 function ,这样,当单击该按钮时,它会触发 AJAX 调用并执行视图中指定的操作。 However, when i click the button, it does not perform action in views.但是,当我单击按钮时,它不会在视图中执行操作。 The code reaches the 'like view' but does not execute anything after 'if request.POST:'.代码到达“like view”,但在“if request.POST:”之后不执行任何操作。 Please help.请帮忙。

Menu.html菜单.html

<form action="{% url 'like'%}" id="plt_{{menu.id}}" data-id="{{menu.id}}" method="post">
        {%csrf_token%}
   <input name="menu_id" type="hidden" value="{{ menu.id }}">
    <div class="like-button" id="btn_{{menu.id}}"></div>
</form>
<script>
     $('.like-button').on('click', function () {
         var id = $(this).attr('id');
         id = id.replace('btn_','');

         $(this).toggleClass('animate').promise().done(function () {
            var link = $("#plt_"+id).attr('action')
                $.ajax({
                    type: 'POST',
                    url: link,
                    headers: {'X-CSRFToken': '{{ csrf_token }}'},
                })
                });
    });

 </script>

Views.py视图.py

def like(request):
    print('reached') //this prints
    if request.POST:
     menu = Menu.objects.get(pk=request.POST.get('menu_id'))
     //execute code to like
     return HTTPResponse('')

Maybe you want to check也许你想检查

if request.is_ajax() and request.method== "POST":

request.POST is a dict.Empty here because body is empty in your request. request.POST在这里是一个 dict.Empty 因为你的请求中的 body 是空的。

Empty dicts are treated like False by python like python 将空字典视为False

if {}:
    print("Hello World") 

Above won't print anything上面不会打印任何东西

But below works但下面的作品

if {"hi" : "there"}:
    print("Hello World")

And docs suggests this check is wrong if request.POST: if request.POST: ,则文档建议此检查是错误的:

It's possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data.有可能一个请求可以通过带有空 POST 字典的 POST 进入 - 例如,如果通过 POST HTTP 方法请求表单但不包含表单数据。 Therefore, you shouldn't use if request.POST to check for use of the POST method;因此,您不应该使用 if request.POST 来检查 POST 方法的使用; instead, use if request.method == "POST" (see HttpRequest.method).相反,使用 if request.method == "POST"(参见 HttpRequest.method)。

It is fairly simple, use serialize() of jquery.相当简单,使用 jquery 的serialize() Serialize function will take all the values from the form, even csrftokenmiddleware which is hidden input type.序列化 function 将从表单中获取所有值,甚至是隐藏输入类型的csrftokenmiddleware So, doing so you will be able to handle post request successfully.因此,这样做您将能够成功处理post请求。 Use sthg like this:像这样使用 sthg:

<script>
     $('.like-button').on('click', function () {
         var id = $(this).attr('id');
         id = id.replace('btn_','');

         $(this).toggleClass('animate').promise().done(function () {
            var link = $("#plt_"+id).attr('action');
            var data = $("#plt_"+id).serialize();   // It will serialize all form data
                $.ajax({
                    type: 'POST',
                    url: link,
                    data: data
                });
         });
    });

 </script>

In views.py do as you do for other request.views.py中做你为其他请求做的事情。 serialize()连载()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM