簡體   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