我有一个以JSON格式组织的文本文件,如下所示:
{
"courseSubject": "Accountancy",
"courseSubject": "American Studies",
"courseSubject": "Anatomy & Regenerative Biology",
"courseSubject": "Anesthesiology",
"courseSubject": "Anthropology",
"courseSubject": "Applied Science",
"courseSubject": "Arabic",
"courseSubject": "Art/Art History"
}

我正在尝试解析我的文本文件并将JSON值添加到我的html选择下拉列表中。请看下面的代码,我不知道我哪里出错:
<html>
<head>
<title>Test</title>
</head>
<body>
<select class="selectpicker" data-style="btn-inverse" data-width="300px">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$.getJSON("courses.txt", function( json ) {
$.each(json, function(key, value) {
$('.selectpicker').append('<option value="' + key + '">' + json[key] + '</option>');
});
</script>
</body>
</html>
&#13;
例如,我希望我的选择选项为: 会计 美国研究, 解剖学&amp;再生生物学等......
答案 0 :(得分:2)
在.
之前添加点($('selectpicker')
),因为您正在使用类选择器,它应该是:
$('.selectpicker').append('<option value="' + val + '">' + json[val] + '</option>');
___^
同时使用for
循环和each
函数。
var json = {
"courseSubject": "Accountancy",
"courseSubject": "American Studies",
"courseSubject": "Anatomy & Regenerative Biology",
"courseSubject": "Anesthesiology",
"courseSubject": "Anthropology",
"courseSubject": "Applied Science",
"courseSubject": "Arabic",
"courseSubject": "Art/Art History"
};
$.each(json, function(key, value) {
$('.selectpicker').append('<option value="' + key + '">' + json[key] + '</option>');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" data-style="btn-inverse" data-width="300px"></select>
&#13;
希望这有帮助。