繁体   English   中英

Django:添加 {% csrf_token %} 时动态 jquery 表单不起作用

[英]Django: Dynamic jquery form not working when {% csrf_token %} is added

我在使用 jquery 的 django 模板中使用动态表单,但是当我向表单添加提交按钮或 csrf 令牌时,动态表单停止工作,我无法再添加新字段。

这是我的 html 文件

 <html> <body> <form method="post"> <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(".add").click(function() { $("form > p:first-child").clone(true).insertBefore("form > p:last-child"); return false; }); $(".remove").click(function() { $(this).parent().remove(); }); </script> </body> </html>

但是当我插入{% csrf_token %}<input type="submit" value="Submit">时,动态表单不起作用

<form method="post">
{% csrf_token %}
<p>
    <label>Name:</label> <input type="text">
    <label>Number:</label> <input type="number">
    <span class="remove">Remove</span>
</p>
<p>
    <span class="add">Add fields</span>
</p>

</form>

,

 <form method="post"> <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> <input type="submit" value="Submit"> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(".add").click(function() { $("form > p:first-child").clone(true).insertBefore("form > p:last-child"); return false; }); $(".remove").click(function() { $(this).parent().remove(); }); </script>

在此添加之后,表单不能再插入/添加新字段。 需要帮忙。

您的选择器如下:

  1. "form > p:first-child" :这将为您提供一个p标签,它是其父标签的第一个子标签,当您将{% csrf_token %}放在p标签之前时,它不再是form标签的第一个子标签.
  2. "form > p:last-child" :当您添加提交按钮时,这将为您提供一个p标签,它是其父标签的最后一个子标签,没有 p 标签是form标签的最后一个子标签。

您可以通过使用:first-of-type:last-of-type选择器来解决此问题,尽管这不是一个非常好的解决方案,并且如果添加其他p标签很容易中断。 如果有多个表单标签等,您的解决方案也很容易中断:

 <form method="post"> {% csrf_token %} <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> <input type="submit" value="Submit"> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(".add").click(function() { $("form > p:first-of-type").clone(true).insertBefore("form > p:last-of-type"); return false; }); $(".remove").click(function() { $(this).parent().remove(); }); </script>

暂无
暂无

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

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