使用 getJSON 显示 div 内的所有对象

Display all objects inside a div with getJSON

我正在尝试将 this Path of Exile API 中的所有对象附加到 Div 中,但继续为 entries: 数组获取 [对象对象]。

当我通过 console.log(index, value) 检查控制台时,我可以看到我想要的一切。

我的代码中还缺少什么来显示来自 "entries: " 的所有 [object object] 数组及其数据?

提前致谢。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.getJSON("http://api.pathofexile.com/ladders/Standard?callback=?", function(result){
                    $.each(result, function(index, value) {
                        console.log(index, value);
                        $("div").append(index + ": " + value + "<br/>");
                    });
                });
            });
        });

    </script>
</head>
<body>

    <button>Klick mich!</button>

    <div></div>

</body>
</html>

如果替换:

$("div").append(index + ": " + value + "<br/>");

与:

$("div").append(index + ": " + JSON.stringify(value) + "<br/>");

应该会显示您想要的所有内容。这么大的数据集可能难以阅读,但仍然有效。

这里的问题是,当 JavaScript 需要一个字符串时,您正在传递一个对象,因此它使用对象的 toString 方法将对象转换为字符串。 toString 方法总是 returns [object Object] 这就是为什么你会收到那个错误。

$("div").append(index + ": " + value + "<br/>"); 行之前,添加一个检查以验证 value 是否是对象,如果是,使用 JSON.stringify.

将其转换为字符串

您可以使用以下代码

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $.getJSON("http://api.pathofexile.com/ladders/Standard?callback=?", function (result) {
          $.each(result, function (index, value) {
            if (value instanceof Object) {
              value = JSON.stringify(value);
            }
            console.log(index, value);
            $("div").append(index + ": " + value + "<br/>");
          });
        });
      });
    });

  </script>
</head>

<body>

  <button>Klick mich!</button>

  <div></div>

</body>

</html>