我正在我的网站的论坛页面上工作,并试图包含编辑和删除发布帖子的用户的帖子功能,如下所示:
function getPosts(){
$.getJSON("fetch_post.php", function(data){
$.each(data, function(i, user){
if (user.parent_id == 0){//if its a post
if ($('.media-wrapper .media[data-id = '+user.id+']').length == 0){//if post does not exist on the page before
var userName = $(".gist_params input.uname").val();
if (userName == user.name){//if logged in user is the originator of this post
var post= //an html showing the post, and then a delete and edit button
}else{//if its another user's post
var post= //an html showing only the post, without delete and edit button
}
$(".media-wrapper").prepend(post);
}
}else{//if its a reply to a post
$.each(data, function(i, user){
if ($('.reply_media .reply_media_body[data-id = '+user.id+']').length == 0){
var par_id = user.parent_id;
var parent_cont = $('.media-wrapper .media[data-id = '+par_id+']');
var reply = //an html showing the reply to the post
parent_cont.find('.media-body .reply_media').prepend(reply);
}
});
}
});
});
}
getPosts();
setInterval(getPosts, 5000);
以下是我删除帖子的代码:
$(document).on("click", ".media .comm_del", function(e){
e.preventDefault();
if (confirm("Are you sure you want to delete the post?")){
var post_id = $(this).attr('del-id');
var post_to_del = $('.media-wrapper').find('.media[data-id = '+post_id+']');
$.post("del_post.php", {"post_id": post_id}, function(data){
if (data = "yes"){
post_to_del.remove();
getPosts();
}
});
}
});
注意:请注意,发布工作正常,所有用户页面都会自动更新。问题在于删除帖子时,只有删除的用户才会看到他/她的Feed上的更新,而其他用户仍然会看到已删除的帖子,直到他们的页面被刷新为止。我想要的是所有用户页面在setInterval
到期时自动更新。
答案 0 :(得分:1)
因此,如果以前没有看到过新帖子,那么您就会添加新帖子,但删除列表中不再包含的旧帖子。
在更新之前,请获取页面上所有当前帖子ID的列表。在查看列表时,请记下您看到的ID。完成后,删除未见
的任何内容。function getPosts() {
var existing = {};
$('.media-wrapper .media[data-id]').each(
function () {
var did = this.getAttribute('data-id');
existing[did] = false;
}
);
$.getJSON("fetch_post.php", function(data) {
$.each(data, function(i, user) {
existing[user.id] = true;
if (user.parent_id == 0) { //if its a post
if ($('.media-wrapper .media[data-id = ' + user.id + ']').length == 0) { //if post does not exist on the page before
var userName = $(".gist_params input.uname").val();
if (userName == user.name) { //if logged in user is the originator of this post
var post = //an html showing the post, and then a delete and edit button
} else { //if its another user's post
var post = //an html showing only the post, without delete and edit button
}
$(".media-wrapper").prepend(post);
}
}
else { //if its a reply to a post
$.each(data, function(i, user) {
if ($('.reply_media .reply_media_body[data-id = ' + user.id + ']').length == 0) {
var par_id = user.parent_id;
var parent_cont = $('.media-wrapper .media[data-id = ' + par_id + ']');
var reply = //an html showing the reply to the post
parent_cont.find('.media-body .reply_media').prepend(reply);
}
});
}
for ( var did in existing )
{
if (! existing[did])
{
$('.media-wrapper .media[data-id=' + did + ']').remove();
}
}
});
});
}