我无法想出一个更合适的标题,但我的问题如下:
我生成一个帖子列表,可以选择喜欢和不喜欢它们,具体取决于它们是否已经被喜欢。
{% for post in posts %}
<hr>
<strong>{{ post.owner }}</strong> </br>
{{ post.content }} </br>
<i>{{ post.post_date }}</i> </br>
<form action="{% url 'like' %}" method="post" class="likeform">
{% csrf_token %}
<input type="hidden" id="post_id" value="{{ post.id }}">
{% if post.id not in liked_posts_ids %}
<button type="submit" >Like</button>
{% else %}
<button type="submit" >Dislike</button>
{% endif %}
</form>
{% endfor %}
现在,与所有使用此类内容的网站一样,我不想每次有人单击“喜欢/不喜欢”按钮时刷新整个网站。
我当前的 JS 如下所示:
$(document).on('submit','.likeform',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'{% url 'like' %}',
data:{
post_id: $('#post_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
$(".likeform").load(" .likeform > *");
}
});
POST 请求工作正常,但 success:function()
部分没有。它刷新所有按钮,这不太好,但它也将所有按钮放在所有形式中。目前我的数据库中有 6 个帖子,在 $(".likeform").load(" .likeform > *");
之后的每个帖子下都有 6 个喜欢/不喜欢按钮已完成。
如何只刷新按钮的正确实例,同时保持 for 循环中生成的按钮?
有没有办法利用 #post_id
识别相关按钮?
最佳答案
由于您说页面上有多个此类表单,因此请丢失 input
上的 id
属性并将其更改为 name
属性。
<input type="hidden" name="post_id" value="{{ post.id }}">
id
必须是唯一的,如果出现多次则无效。 name
属性是输入元素的更好标识符。
在您的 $.ajax
函数中,您需要从已提交的当前表单中获取值。在该表单中,您要选择所需的所有元素。
现在,对于请求,您需要做一些不同的事情。该请求应该发送到服务器上的一个函数,该函数会使用我们发送的 id 更新该帖子的值(如果该帖子被喜欢或不喜欢)。没有进一步的了。然后,作为响应,它应该发送回一个文本字符串,该文本字符串将成为提交按钮的新文本值。
在您的 success
处理程序中,您需要将收到的文本字符串设置为提交表单中的按钮。因此,当您点击Like
时,服务器将发送一个请求,该帖子将在服务器上被点赞,然后服务器返回Dislike
,这就是现在帖子上的文本按钮。当点击“不喜欢”时,它应该做同样的事情,不喜欢该帖子并返回 Like
字符串。
$(document).on('submit', '.likeform', function(e) {
e.preventDefault();
// Get the currently submitted form and find the inputs
// inside the form necessary to send the data with.
var $form = $(this);
var $postId = $form.find('input[name="post_id"]');
var $csrf = $form.find('input[name="csrfmiddlewaretoken"]');
var $button = $form.find('button');
$.ajax({
type: 'POST',
url: '{% url 'like' %}',
dataType: 'text',
data: {
post_id: $postId.val(),
csrfmiddlewaretoken: $csrf.val()
},
success: function(response) {
// Replace the current text of the button with a new
// text based on if it was liked or disliked.
$button.text(response);
}
});
});
关于javascript - Ajax/jQuery Django 刷新元素类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59976692/