javascript - 将 JSON 数据绑定到 HTML 元素
问题描述
我想将 JSON 数据绑定到<select>
元素。我创建了 HTML 页面。让我知道我错在哪里。看看我试过什么..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function clickMe() {
// THE JSON ARRAY.
var cars = [
{
"ID": "001",
"Car_Name": "BMW"
},
{
"ID": "002",
"Car_Name": "AUDI"
},
{
"ID": "003",
"Car_Name": "Range Rover"
}
];
var ele = document.getElementById('sel');
for (var i = 0; i < cars.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
ele.innerHTML = ele.innerHTML +
'<option value="' + cars[i]['ID'] + '">' + cars[i]['Car_Name'] + '</option>';
}
}
function show(ele) {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
msg.innerHTML = 'Selected Car: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' +
'ID: <b>' + ele.value + '</b>';
}
</script>
</head>
<body>
<div>
<div>
<!--Click button-->
<p style="margin-top:20px;">
<input type="button" onclick="clickMe"value="Click to Select" />
</p>
<!--Select Menu-->
<p>
<select id="sel" onchange="show(this)">
<option value=""> - - Select - -</option>
</select>
</p>
<p id="msg">
</p>
</div>
</div>
</body>
</html>
解决方案
在我看来,你应该试试ajax。
$.ajax({
url:'test.html',
type:'POST',
data: 'test =' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
推荐阅读
- javascript - how integrate a scroll-down effect with velocity.js in a react application without jquery?
- mongodb - Connecting Android Studio with MongoDB
- html - 如何将此 div 标签放在框的右侧?
- c++ - ffmpeg mpg 转 jpg
- python - 使用非 ascii 字符从 csv 文件中删除 null
- hyperledger-fabric - 第一个网络示例:调用期间的背书失败
- laravel - 在 laravel 数据库中上传后在浏览器中显示图像文件
- c# - C# Discord bot 获取发件人头像
- scala - Spark Streaming 标准示例中缺少所需的配置“bootstrap.servers”错误
- sql - 从没有任何格式的日期中提取时间