我正在尝试使用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查询计算喜欢并取得了成功。
答案 0 :(得分:1)
更改为以下内容:
JS代码:
$(document).ready(function(){
$("#comment_form").submit(function(event){
event.preventDefault();
var article_id = $(this).find('.article_id').value();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "post",
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>");
}
}
});
return false;
});
});
Django模板:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
答案 1 :(得分:1)
试试这个
</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>
$(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*/
}
});
});
});