如何使用Ajax替换(Django表单的{%csrf_token%})

时间:2015-07-28 03:06:02

标签: javascript jquery ajax django replacewith

我正在尝试用我的Django应用程序中的表单替换“回复”按钮。

enter image description here

这是我的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

我得到了表单元素,但问题是{%csrf_token%}在replaceWith()中被处理为unicode。 Django需要{%csrf_token%}来提交表单。任何形式的帮助和建议都会感激不尽:)

enter image description here

修改 我假设{%}}意味着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>'); 

该段落将出现。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

要在javascript中使用django模板语言,您应该将代码封装在Verbatim标记中。

示例:

{% verbatim %}  
    var hello = {% if some_condition %} 'World' {% else %} 'foobar' {% endif %};
{% endverbatim %}

来自文档: 停止模板引擎呈现此块标记的内容。 常见的用途是允许JavaScript模板层与Django的语法冲突

在您的情况下:

<script>
    {% verbatim  %}
        $(document).on('click', '.comment-reply-link', function(e) {
            $(this).replaceWith("<form method='post'>  {% csrf_token %}  </form>")
        };
    {% endverbatim %}
</script>