javascript - 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.
解决方案
您可以使用以下代码执行此操作
$.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)
.
推荐阅读
- arrays - 使用递归指针的 OpenACC 并行 FOR 循环
- mysql - 在列中显示值,尽管它被另一列的 WHERE 条件排除
- aem - 在页面属性对话框中隐藏继承的属性(触摸 UI)
- xamarin.forms - Xamarin 应用程序中的错误连接超时
- python - 为什么pytorch和scratch代码中的正则化不匹配,pytorch中用于正则化的公式是什么?
- sql - 如何通过从一个中提取最大数字然后到另一个来连接两个 SQL 表?
- jasperserver - JasperServer 的工作历史
- python - ssh 运行命令给出了与在本地运行它不同的结果
- c# - 安慰检查 C# 中是否存在特定队列?
- c# - c# ef core RemoveRange 约束冲突