我试图从数据库调用中填充我的Web应用程序上的静态内容,该数据库调用返回一个JSON元素列表,然后我想让Option 1填充..
JSON returned:
{id: 0, categoryName: "General Discussion"},
.
.
.
{id: 7, categoryName: "Cleaning and Repairs"}
我的电话:
$.get("http://localhost:8080/cc/sc/cat").done(function(categories) {
var catList = document.getElementById("categories");
var option = document.createElement("option");
for (category in categories){
console.log("value: " + categories[category].categoryName);
option.text = categories[category].categoryName;
catList.add(categories[category].categoryName);
}
});
HTML内容
<select id="categories" class="form-control"></select>
错误:
(index):116 Uncaught TypeError: Failed to execute 'add' on 'HTMLSelectElement': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'
at Object.<anonymous> ((index):116)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at y (jquery.min.js:4)
at XMLHttpRequest.c (jquery.min.js:4)
感谢任何帮助。
答案 0 :(得分:1)
试试这个
$.get("http://localhost:8080/cc/sc/cat").done(function(categories) {
for (category in categories){
$('#categories').append('<option>'+categories[category].categoryName+'</option>')
}
});
答案 1 :(得分:0)
您必须打包选项,为您的选择生成数据,如下例所示。
function generateSelect(){
var categories = [{id: 1, categoryName: "General Discussion"},{id: 2, categoryName: "Cleaning and Repairs"}];
var catList = document.getElementById("categories");
for (var a = 0; a< categories.length; a++){
var option = document.createElement("option");
option.value = categories[a].id;
option.text = categories[a].categoryName;
catList.append(option);
}
}