通过 HTTP 请求从 JSON 数据库填充 ul

问题描述

我被这个问题困住了。我有一个 JSON DB,我想通过 HTTP 从中请求数据。在那之后,我想用我得到的数据作为答案使 li's 在一个 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 中注入数据。

解决方法

您可以使用以下代码执行此操作

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

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