【发布时间】:2023-03-28 06:38:01
【问题描述】:
我正在使用 Django、jQuery 和 Ajax。但是,我对如何在 ajax 数据中获取帖子 ID 以在 views.py 中使用它感到困惑。我在这里添加代码,并且必须阅读代码中的 cmets,以便您可以更好地理解我实际试图解释的内容或我面临的问题。如果这个问题比回答其他问题需要你多一点时间,如果你知道解决方案,请不要跳过这个问题。我能为你做的就是给你投票 10 到 15 个答案,这样你的声誉就会提高。
我是 JQuery 的初学者,所以请简要解释一下你的答案。
所以,在下面我有 div 标签,它将为我提供帖子 ID。如果用户点击回复按钮。
<div id='post_id' post="{{post.id}}">
{% if node.level < 3 %}
<button class='btn btn-success' onclick="myFunction({{node.id}})">Reply</button>
{% endif %}
</div>
我也有评论的表格。
<form id='commentform' class='commentform' method='POST'>
{% csrf_token %}
{% with allcomments as total_comments %}
<p>{{ total_comments }} comment{{total_comments|pluralize}}</p>
{% endwith %}
<select name='post' class='d-none' id='id_post'>
<option value="{{ post.id }}" selected="{{ post.id }}"></option>
</select>
<label class='small font-weight-bold'>{{comment_form.parent.label}}</label>
{{comment_form.parent}}
<div class='d-flex'>
<img class='avatar_comment align-self-center' src="{% for data in avatar %}{{data.avatar.url}}{%endfor%}">
{{comment_form.body }}
</div>
<div class='d-flex flex-row-reverse'>
<button type='submit' class='newcomment btn btn-primary' value='commentform' id='newcomment'>Submit</button>
</div>
</form>
在脚本标签之间我设置了一个与表单链接的事件。
$(document).on('click', '#newcomment, #newcommentinner', function (e) {
e.preventDefault();
var button = $(this).attr("value");
var post_id = document.getElementById('post_id').getAttribute('post'); #Here I am trying to take post id from div tag with id='post_id'.
console.log(post_id,'postid') #In console it is returning me 2 which is right post id.
var placement = "commentform"
if (button == "newcommentform") {
var placement = "newcommentform"
}
$.ajax({
type: 'POST',
url: '{% url "posts:addcomment" pk=post.pk slug=post.slug %}',
data: $("#" + button).serialize() + {'post_id' : post_id},#Here I am trying to take that post id in data so i can use that in views.py. But in views.py it is returning me none And I don't understand why ? Because this is a post_id variable which is returning me 2 in console but in terminal it is returning me none. Please tell me how can i fix it.
cache: false,
success: function (json) {
console.log(json)
$('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \
<div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \
<div>' + json['result2'] + '</div> \
<hr> \
</div>').insertBefore('#' + placement);
$('.commentform').trigger("reset");
formExit()
},
error: function (xhr, errmsg, err) {
}
});
})
如果需要更多信息,请告诉我。我会用这些信息更新我的问题。
【问题讨论】:
-
嗨,post_id 在选择框中?
-
是的,这是帖子 ID
-
这里还有
post="{{post.id}}"是postid 吗?然后,如果您正在调用 jquery onclick of button,则只需使用$(this).attr('post')获取postid的值。 -
嗯,我想我没有正确解释我的问题,但现在您可以再次看到我的问题。我已经更新了,所以你可以更好地理解。如果你能回答这个问题,那将有很大帮助。谢谢。
-
这样传递
data: $("#" + button).serialize() +"&post_id="+post_id
标签: html jquery django ajax django-templates