Javascript 从db调用动态填充选择标记选项
我试图通过一个数据库调用在我的web应用程序上填充静态内容,该调用返回一个JSON元素列表,然后我想让选项1填充这些元素Javascript 从db调用动态填充选择标记选项,javascript,html,json,Javascript,Html,Json,我试图通过一个数据库调用在我的web应用程序上填充静态内容,该调用返回一个JSON元素列表,然后我想让选项1填充这些元素 JSON returned: {id: 0, categoryName: "General Discussion"}, . . . {id: 7, categoryName: "Cleaning and Repairs"} 我的电话: $.get("http://localhost:8080/cc/sc/cat").done(function(categor
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)
感谢您的帮助。试试这个
$.get("http://localhost:8080/cc/sc/cat").done(function(categories) {
for (category in categories){
$('#categories').append('<option>'+categories[category].categoryName+'</option>')
}
});
您必须包装您的选项,为您的选择生成数据,如下例所示
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);
}
}
可能重复的