gpt4 book ai didi

javascript - 在新数组项上附加 ajax 中的 PHP 数组项

转载 作者:行者123 更新时间:2023-11-30 10:19:17 26 4
gpt4 key购买 nike

我正在尝试做的是使用 ajax/jQuery 方法检测然后收集新的 PHP 数组对象(有点像 api)。

{
"posts": [
{
"id": "77",
"post": ""Oh cool bro"",
"time": "Mar 02, 2014"
},
{
"id": "76",
"post": "Ohh",
"time": "Mar 02, 2014"
},
{
"id": "75",
"post": "Yupp",
"time": "Mar 02, 2014"
},
{
"id": "74",
"post": "This is content",
"time": "Mar 02, 2014"
}
]
}

我正在尝试使用 ajax 检测数组中的新变化,如果用户提交新帖子,数组会实时更新为 id 78 的帖子。我希望能够检测到添加并仅添加新帖子。此外,我希望提要能够每 5 秒检查一次新帖子,并附加新帖子而不是重新附加所有帖子。几乎和 facebook 的 feed ticker 一样。

我的 jQuery/ajax 代码:

function getFeed() {
$.ajax({
type: "GET",
url: "api.php",
dataType: 'json',
success: function(data) {
var posts = data.posts
$.each(posts, function(i) {
$('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
});
}
});
}

最佳答案

为什么不将当前帖子 ID 存储在 JavaScript 数组中?

//An array that will contain the IDs of posts that have already
//been appended.
var displayedPosts = new Array();

//Function to get feed.
function getFeed() {
$.ajax({
type: "GET",
url: "api.php",
dataType: 'json',
success: function(data) {
var posts = data.posts
$.each(posts, function(i) {
//Make sure that this post hasn't already been added.
if($.inArray(posts[i].id, displayedPosts) === -1){
//Store the ID of the post so that we don't add it again.
displayedPosts.push(posts[i].id);
//Append
$('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
}
});
}
});
}

我必须指出,更好 的解决方案是使用发送到 api.php 的时间戳参数。即给我所有在特定时间戳后发布的帖子(在这种情况下,您将发送最后一篇帖子的时间戳作为参数)。这样,您就不会重复向客户端发送相同的数据。

关于javascript - 在新数组项上附加 ajax 中的 PHP 数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22153115/

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