Reputation: 122450
In a JQuery getJSON
call, how can I tell the length of the JSON that's returned?
function refreshRoomList() {
$.getJSON('API/list_rooms',
function (rooms) {
if (rooms.length > 0) {
$("#existing-room-list").empty();
$("#join-existing-room").text("Join existing room:"); // this shouldn't be here
$.each(rooms, function (index, roomName) {
var newChild = sprintf('<li><a href="room?key=%s">%s</a></li>', index, roomName);
$("#existing-room-list").append(newChild);
});
}
else {
$("#join-existing-room").text("No rooms found.");
}
});
}
For some reason this doesn't work, but if I replace rooms.length > 0
with true
, the full list of rooms is printed out.
If rooms
is empty, it is returned as {}
.
Upvotes: 2
Views: 5500
Reputation: 1108722
If rooms is empty, it is returned as {}.
Thus, it's not an array, but an object. Objects doesn't have a length. There's only one of it. If you want to denote nothing, then rather use null
instead of {}
. This way you can use if (rooms)
instead.
To learn more about JSON, you may find this article useful.
Upvotes: 3
Reputation: 630399
Try this approach instead, in your situation it should be null when empty:
if (rooms) {
Upvotes: 0