首页 > 解决方案 > 显示 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.");
    }
}

任何帮助,将不胜感激。

谢谢!

(如果我的问题不清楚,我可以尝试提供更多信息)

标签: phpjquery

解决方案


您已经知道它在使用$.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);
    });
}

推荐阅读