gpt4 book ai didi

javascript - 无法使用ajax添加评论

转载 作者:行者123 更新时间:2023-12-02 16:42:50 25 4
gpt4 key购买 nike

我正在尝试使用ajax添加评论。这是我的 ajax 代码:

$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = {{article.id}};
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "get",
success: function(result){

if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = "comment"><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
});

});

这是我在 django 模板中添加注释的形式:

</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}

</div>

尝试调试时,我注意到它甚至没有进入ajax主体。那我做错了什么?我已经完成了 ajax 查询并计算了点赞数,并取得了成功。

最佳答案

试试这个

HTML

</div>
{% if username %}
<form action="#" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="text" name = "article" value="{{ article.id }}" id = "article_id">
<input type="text" name = "comment" value="comment goes here" id = "comment_text">
<input type="submit" class="button" value="???????? ???????????" id = "add_comment">
</form>
{% endif %}

</div>

jQuery

  $(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = $('#article_id').val();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "POST", /*i belive you are posting data to BE api*/
data:{'comment':"your comment goes here"}, /* use this get what given in input $("#comment_text").val()*/
success: function(result){
/*process data after success call*/
}
});
});

});

关于javascript - 无法使用ajax添加评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27352013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com