【问题标题】:JQuery: Get length of JSON reply?JQuery:获取 JSON 回复的长度?
【发布时间】:2010-04-07 18:21:19
【问题描述】:

在 JQuery getJSON 调用中,我如何知道返回的 JSON 的长度?

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.");
              }
          });
}

由于某种原因,这不起作用,但如果我将 rooms.length &gt; 0 替换为 true,则会打印出完整的房间列表。

如果rooms 为空,则返回为{}

【问题讨论】:

  • 返回的 JSON 有效负载是在方括号 [] 还是大括号 {} 内?
  • users.length 有什么问题?
  • 我想我用错了。见上文。
  • 哦,我以为那是讽刺。它以对象字面量语法返回。
  • @Rosarch: 唷,现在我们已经解决了这些问题,如果返回 null 对您不利,请参阅 api.jquery.com/jQuery.isEmptyObject

标签: javascript jquery ajax json


【解决方案1】:

如果房间为空,则返回为 {}。

因此,它不是一个数组,而是一个对象。对象没有长度。只有一个。如果您想表示nothing,那么请使用null 而不是{}。这样你就可以改用if (rooms)了。

要了解有关 JSON 的更多信息,您可能会发现 this article 很有用。

【讨论】:

    【解决方案2】:

    请尝试这种方法,在您的情况下,它应该为空时为空:

    if (rooms) {
    

    【讨论】:

    • 这看起来像是在我的最小初始测试中工作。谢谢。
    • @Rosarch:我认为你需要更多测试;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多