php - 显示 json 字符串中的所有对象
问题描述
我正在尝试通过它获取 json 字符串中的所有对象$.getJSON
并且它可以工作,但是我无法全部显示它们(它只显示最后一个对象)。我知道它是因为它覆盖了每个条目,.$each
但我不知道如何解决这个问题,因为我试图附加它,但它只是多次显示每个条目(我将它设置为每 5 秒更新一次,到看看是否有更多条目可用)。无论如何,这是我的代码(jQuery和PHP)
jQuery 代码 -
$(function() {
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// how to display each friend online without overwriting each one to only display the last. :/
$('#friends-online').html("<a href=\"/members/chat/" + value.id + "\" class=\"chat-with\">" + value.name + "</a><br>");
});
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
setInterval(function() {
buildOnlineFriendList();
}, 5000);
buildOnlineFriendList();
});
PHP 代码 -
public function getFriendsOnline()
{
$query = $this->connection->execute("SELECT members.username AS friend_username, friends_online.user_id AS fo_id FROM friends_online, friends, members
WHERE friends_online.user_id = friends.friend_id AND members.id = friends.friend_id AND friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
// get the id/username of the friend(s) online
foreach ($query as $values) {
$friends_online[] = array('id' => $values['fo_id'], 'name' => $values['friend_username']);
}
return $friends_online;
} else {
throw new FriendsException("No friends are online.");
}
}
任何帮助,将不胜感激。
谢谢!
(如果我的问题不清楚,我可以尝试提供更多信息)
解决方案
您已经知道它在使用$.each
. friends-online
问题是它为每个循环的元素编写 HTML 。您需要做的就是在变量中设置该值并在每次迭代中更新该变量。然后在循环完成后,设置元素的 HTML。我已将您的功能修改为:
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
// create a variable to hold the html string
var html = "";
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// set the value of the html here
html += "<a href=\"/members/chat/" + value.id + "\" class=\"chat-with\">" + value.name + "</a><br>";
});
// set the html here, after the loop.
$('#friends-online').html(html);
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
推荐阅读
- mysql - 字段列表中的 MySQL 未知列。触发原因?
- angular - 角度形式验证`min`不起作用
- android - Android 对话框未正确调整大小
- python - 什么时候调用 callable() 仍然会失败?
- javascript - Javascript - 转换隐藏/显示 FX
- vba - 将列表框中的选定行插入工作表
- angular - Angular 6 RxJs:尝试使 obj 可观察以用于其他组件
- html - Bigcommerce 模具附加付款结帐按钮未显示在快速购物车和购物车视图页面上?
- php - 用两条新线代替双倍
不起作用 - java - 从文件中填充 N 叶树