![](/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.