Я пытаюсь заменить кнопку «ответить» формой в приложении Django.Как Ajax replaceWith (Django form {% csrf_token%})
Вот мой код 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(). {% csrf_token%} необходимо в Django для отправки формы. Любой вид помощи и советов будет благодарен :)
Edit: Я предполагаю, что {%%} означает, что Джанго должен быть вовлечен, чтобы получить правильное значение. Поэтому я подумал, что должен отобразить 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>');
этот параграф появится. Есть предположения?
вы пробовали https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/# ajax? –
Я добавил, что Javascript getCookie() из документации в мой javascript и декораторы (csrf_protect и security_csrf_cookie) к моей функции просмотра, но это не сработало ... Я использовал это неправильно? – YOUNG
Ну, вместо того, чтобы использовать ajax для визуализации формы, почему бы не просто создать форму под кнопкой «ответить» со стилем отображения: none ;, а затем, когда щелкнут «ответ», покажите форму и используйте jquery 'hide' для скрыть кнопку ответа? –