,您可以按照以下步骤进行操作:
{
"brands": [
"品牌1",
"品牌2",
"品牌3",
...
]
}
以下是一个示例代码,帮助您更好地理解如何从JSON数据库获取汽车品牌名称数据:
car_brands.json 文件内容:
{
"brands": [
"奥迪",
"宝马",
"奔驰",
"本田",
"丰田",
"福特",
"大众",
"现代",
"雪佛兰"
]
}
Node.js 服务器端代码:
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('car_brands.json', 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
const carBrands = JSON.parse(data).brands;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(carBrands));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
HTML 页面代码:
<!DOCTYPE html>
<html>
<head>
<title>汽车品牌选择</title>
</head>
<body>
<select id="carBrandsSelect">
<option value="">请选择汽车品牌</option>
</select>
<script>
const carBrandsSelect = document.getElementById('carBrandsSelect');
fetch('http://localhost:3000')
.then(response => response.json())
.then(data => {
data.forEach(brand => {
const option = document.createElement('option');
option.value = brand;
option.text = brand;
carBrandsSelect.appendChild(option);
});
})
.catch(error => console.error(error));
</script>
</body>
</html>
请注意,上述示例代码仅供参考,您需要根据实际情况进行修改和调整。此外,这只是从JSON数据库中获取汽车品牌名称数据的一种方法,还有其他不同的实现方式,取决于您使用的技术栈和具体要求。
领取专属 10元无门槛券
手把手带您无忧上云