简体   繁体   English

Django 项目中的 Jquery 脚本未检测到表单提交

[英]Jquery script in Django project isn't detecting form submission

I'm creating a website using Django, and using Ajax to prevent site reload after submitting a form.我正在使用 Django 创建一个网站,并使用 Ajax 来防止在提交表单后重新加载网站。 Right now, I have orders being displayed on the site with an x button beside each order.现在,我有订单显示在网站上,每个订单旁边都有一个 x 按钮。 Clicking the x cancels the order on the database (a post request that changes a value rather than simply deleting it) and also reloads the div in which the orders are housed.单击 x 会取消数据库上的订单(更改值而不是简单地删除它的发布请求)并且还会重新加载放置订单的 div。 I have other forms on this website that are working correctly (they do have fields, though and use crispyforms).我在这个网站上有其他 forms 工作正常(虽然它们确实有字段并且使用了crispyforms)。 The problem I'm facing is that the script isn't detecting that the form is submitted.我面临的问题是脚本没有检测到表单已提交。

Here are the pertinent parts of my project:以下是我项目的相关部分:

views.py视图.py

class CancelForm(ModelForm):
 class Meta:
    model = Order
    fields = ['Filled']
...
def cancelorder(request, pk):
    form = CancelForm(request.POST)
    if request.is_ajax and request.method == "POST":
        order = Order.objects.get(pk=pk)
        order.Filled = "C"
        instance = order.save(update_fields=["Filled"])
        return JsonResponse({"canceled": pk}, status=200)
    return JsonResponse({"error": ""}, status=400)

urls.py网址.py

urlpatterns = [
    path('', views.orderpage, name="order-index"),
    path('cancel_order/<int:pk>/', views.cancelorder, name="cancel_order"),
    path('post/ajax/order/', views.postorder, name = "post_order"),
    path('yourorders/', views.yourorders, name="your_orders"),
    path('allorders/', views.allorders, name="all_orders"),
]

orderpage.html (this is my main page, with the div that is to be reloaded on yourorders.html) orderpage.html (这是我的主页,将在 yourorders.html 上重新加载 div)

<div class="container-fluid ActiveOrderInfoDiv" id="YourOrdersDiv">
  {% include 'order/yourorders.html' %}
</div>

yourorders.html yourorders.html

{% for order in all_orders %}
  <div class="row">
...
    <div class="col">{{ order.OrderID }}</div>
    <form action="{% url 'order:cancel_order' pk=order.OrderID %}" id="cancel_button" method="POST">
      {% csrf_token %}
      <button type="submit" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </form>
  </div>
  {% endfor %}

Javascript (here, check 2 is never logged) Javascript(此处,从未记录检查 2)

 $(document).ready(function () {
      $("#cancel_button").submit(function (e) {
          console.log("check 2");
          e.preventDefault();
          console.log("check 3");
          $.ajax({
            url: "{% url 'order:your_orders' %}",
            success: function (response) {
              $("#YourOrdersDiv").load("/order/yourorders/");
            },
            error: function (response) {
            }
          });
        });
    });

What I've tried我试过的

  • Moved the script to yourorders.html (I thought maybe the JS wasn't seeing the cancel_button ID)将脚本移动到yourorders.html (我想也许 JS 没有看到 cancel_button ID)
  • Used console.log to see where the flow stopped (it doesn't seem to pick up that the cancel button was submitted)使用 console.log 查看流程停止的位置(似乎没有发现取消按钮已提交)
  • Added the CancelForm modelform (previously I was updating the DB without a modelform)添加了 CancelForm 模型表单(以前我在没有模型表单的情况下更新数据库)
  • Generally poking around with Ajax syntax and order通常使用 Ajax 语法和顺序
  • Looking at other questions here on StackOverflow - I seem to be following them, and my syntax may just be right, it's just not picking up that the cancel_button form is being submitted在 StackOverflow 上查看其他问题 - 我似乎在关注它们,我的语法可能是正确的,只是没有发现正在提交 cancel_button 表单

You should delegate the event handler to the document level so that when the form is reloaded the event is still handled.您应该将事件处理程序委托给文档级别,以便在重新加载表单时仍然可以处理事件。 When you "reload" the form you are inserting a new element into the DOM that does not have the event handler attached to it当您“重新加载”表单时,您将一个新元素插入到没有附加事件处理程序的 DOM 中

$(document).on("submit", "#cancel_button", function(e) {
  ...

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

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