【问题标题】:Populate an ul from a JSON database by HTTP request通过 HTTP 请求从 JSON 数据库填充 ul
【发布时间】:2021-05-23 16:05:38
【问题描述】:

我被这个问题困住了。我有一个 JSON 数据库,我想通过 HTTP 从它请求数据。在那之后,我想用我得到的数据作为答案,把 li 放在一个 ul 中。这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>X</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <script>
        function requestBrands()
    {
        adress="http://localhost:3000/brands?callback=?"
        $.getJSON(adress ,function(answer)
        {
            var ul = document.getElementById("x");
            $.each(answer, function(index, brands)
            {               
                ???????
            }
            )
        }
        )
    };
    </script>
</head>
<body>

<div>
<button onclick="solicitareMarca()">Brands categ</button>
</div>

<div >
    <h3">Brands</h3>
    <ul id="x">
    </ul>
</div>

</body>
</html>

JSON 数据库:

{
  "brands":[
    {
      "id":1,
      "name":"Audi"
    },
    {
      "id":2,
      "name":"BMW"
    }
  ]
}

我找不到如何在 ul 中注入数据。

【问题讨论】:

  • 在您的代码中,answer 是整个对象,具有brands 属性。这是一个对象,所以你不能做$.each(answer...。你可以做answer.brands.forEach((brand, i) =&gt; { /* ... */ });

标签: javascript json localhost httprequest


【解决方案1】:

你可以使用下面的代码来做到这一点

 $.each(answer.brands, function(index, brand)
 {               
    $("#x").append(`<li> Id:${brand.id} Car name: ${brand.name} </li>`);
 }       

但由于您的答案包含作为数组的品牌,因此请将 answer.brands 作为参数传递给 $.each(answer.brands) 函数而不是 $.each(answer)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2015-08-16
    • 2014-08-28
    • 1970-01-01
    • 2012-07-25
    • 2011-03-18
    相关资源
    最近更新 更多