【发布时间】:2015-07-28 22:39:16
【问题描述】:
我正在尝试用我的 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
我得到了表单元素,但问题是 {% csrf_token %} 在 replaceWith() 中仅作为 unicode 处理。 {% csrf_token %} 在 Django 中是提交表单所必需的。任何形式的帮助和建议将不胜感激:)
编辑: 我假设 {% %} 意味着需要 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>
回复.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 页面变量 results 得到正确的 html 页面数据,但看起来像
$(item).html(reply_form);
工作不正常。因为当我这样做时
$(item).html('<p>button disappears</p>');
段落将出现。有什么想法吗?
【问题讨论】:
-
我将文档中的 Javascript getCookie() 添加到我的 javascript 中,并将装饰器(csrf_protect 和 ensure_csrf_cookie)添加到我的视图函数中,但它没有工作....我用错了吗?
-
好吧,与其用ajax渲染一个表单,不如直接把你的表单放在“回复”按钮下,样式显示:none;,然后当点击“回复”时,显示表单并使用 jquery
hide隐藏回复按钮?
标签: javascript jquery ajax django replacewith