繁体   English   中英

如何在 Django 中处理 AJAX POST 请求

[英]How to handle AJAX POST request in Django

我的应用程序中有一种 twitter 之类的按钮 function ,这样,当单击该按钮时,它会触发 AJAX 调用并执行视图中指定的操作。 但是,当我单击按钮时,它不会在视图中执行操作。 代码到达“like view”,但在“if request.POST:”之后不执行任何操作。 请帮忙。

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

视图.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('')

也许你想检查

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

request.POST在这里是一个 dict.Empty 因为你的请求中的 body 是空的。

python 将空字典视为False

if {}:
    print("Hello World") 

上面不会打印任何东西

但下面的作品

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

if request.POST: ,则文档建议此检查是错误的:

有可能一个请求可以通过带有空 POST 字典的 POST 进入 - 例如,如果通过 POST HTTP 方法请求表单但不包含表单数据。 因此,您不应该使用 if request.POST 来检查 POST 方法的使用; 相反,使用 if request.method == "POST"(参见 HttpRequest.method)。

相当简单,使用 jquery 的serialize() 序列化 function 将从表单中获取所有值,甚至是隐藏输入类型的csrftokenmiddleware 因此,这样做您将能够成功处理post请求。 像这样使用 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>

views.py中做你为其他请求做的事情。 连载()

暂无
暂无

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

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