首页 > 解决方案 > Populate an ul from a JSON database by HTTP request

问题描述

I am stuck on this problem. I have an JSON DB and I want to request data from it by HTTP. After that, I want to make li's in an ul with the data I got as answer. Here is my code:

<!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 DB:

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

I can't find how to inject the data in the ul.

标签: javascriptjsonlocalhosthttprequest

解决方案


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

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

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


推荐阅读