![](/img/trans.png)
[英]How to properly append django csrf_token to form in inline javascript?
[英]How to Ajax replaceWith(Django form's {% csrf_token %})
我正在嘗試用Django應用程序中的表單替換“回復”按鈕。
這是我的Javascript代碼:
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'>{% csrf_token %}<div class='form-group'><label for='comment'>Comment:</label><textarea class='form-control' id='comment' rows='5' maxlength='300' minlength='1' name='comment' placeholder='Tell us how you loved this product :D'></textarea></div><button type='submit' name='post_comment' value='True'>Comment</button></form>");});
// The replacing line should contain no whitespace.
// Otherwise it will raise Uncaught SyntaxError: Unexpected token ILLEGAL
我得到了form元素,但問題是{%csrf_token%}在replaceWith()中只是作為Unicode處理。 在Django中,必須使用{%csrf_token%}才能提交表單。 任何形式的幫助和建議將不勝感激:)
編輯:我假設{%%}意味着Django需要參與以檢索正確的值。 因此,我認為我應該使用表單呈現html頁面,並使用“回復”按鈕更新該表單。 這是我的邏輯。
view.html
<div class="reply">
<a class='comment-reply-link' href='{% url "rango:reply_form" %}'aria-label='Reply to Araujo'>Reply</a>
</div>
Reply.js
function ajax_get_update(item){
$.get(url, function(results){
//get the parts of the result you want to update. Just select the needed parts of the response
// var reply_form = $("#reply_form", results);
var reply_form = $(".head", results);
console.log(reply_form);
//console.log(results);
//update the ajax_table_result with the return value
$(item).html(reply_form);
}, "html");
}
$(document).on('click', '.reply', function(e) {
console.log("Debuggin...");
e.preventDefault();
url = ($( '.comment-reply-link' )[0].href);
console.log(url);
ajax_get_update(this);
});
reply_form.html
<!DOCTYPE html>
... code omitted ....
<form id="reply_form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="comment">Reply:</label>
<textarea class="form-control" id="comment" rows="5" maxlength="300" minlength="1" name="comment" placeholder="Tell us how you loved this product :D"></textarea>
</div>
<button type="submit" name="post_comment" value="True">Reply</button>
</form>
</body>
</html>
當我單擊“答復”按鈕時,該按鈕消失,但沒有任何更新。 html頁面變量結果獲取正確的html頁面數據,但似乎
$(item).html(reply_form);
工作不正常。 因為當我做
$(item).html('<p>button disappears</p>');
該段將出現。 有什么想法嗎?
要在javascript中使用django模板語言,您應該將代碼封裝在Verbatim標記中。
例如:
{% verbatim %}
var hello = {% if some_condition %} 'World' {% else %} 'foobar' {% endif %};
{% endverbatim %}
來自docs:停止模板引擎呈現此block標記的內容。 通常的用途是允許與Django語法沖突的JavaScript模板層
在您的情況下:
<script>
{% verbatim %}
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'> {% csrf_token %} </form>")
};
{% endverbatim %}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.