我正在使用json数据创建一个下拉菜单。为什么没有任何数据填充?我也尝试直接在网址arg中直接输入“ fitmentData.json”,但没有任何帮助。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>
<body>
<select name="year" id="year">
</select>
</body>
<script>
let dropdown = $('year');
dropdown.empty();
dropdown.append('<option selected = "true" disabled>Choose
Year</option>');
dropdown.prop('selectedIndex', 0);
const url = 'fitmentData.json';
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value',
entry.year).text(entry.year));
})
});
</script>
</html>
fitmentData.json
[
{
"brand": "Yamaha",
"model": "YZ100",
"year": "1981"
},
{
"brand": "Suzuki",
"model": "RM100",
"year": "1978"
},
{
"brand": "Yamaha",
"model": "WR250F",
"year": "2011"
},
{
"brand": "Suzuki",
"model": "PE175",
"year": "1978"
}
]
是的,我确保jquery首先工作。
答案 0 :(得分:1)
您的选择器应该是#year
,而不是year
。
let dropdown = $('#year');
dropdown.empty();
dropdown.append('<option selected = "true" disabled>Choose Year</option>');
dropdown.prop('selectedIndex', 0);
const url = 'fitmentData.json';
let data = [
{
"brand": "Yamaha",
"model": "YZ100",
"year": "1981"
},
{
"brand": "Suzuki",
"model": "RM100",
"year": "1978"
},
{
"brand": "Yamaha",
"model": "WR250F",
"year": "2011"
},
{
"brand": "Suzuki",
"model": "PE175",
"year": "1978"
}
]
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value',
entry.year).text(entry.year));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="year" id="year">
</select>
答案 1 :(得分:0)
我找到了答案。我正在使用谷歌浏览器并收到此错误 jquery.min.js:2从原始'null'的'file:///Users/macbookuser/Desktop/json_dropdown_filter/fitmentData.json'处对XMLHttpRequest的访问已被CORS策略阻止:协议方案仅支持跨原始请求:http,数据,chrome,chrome扩展名,https。
我切换到了firefox,并且填充了json数据。