如何解决通过 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)
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。