我想从JSON文件加载到datalist
。我的JSON文件有2个属性,如下所示:
[ {
"product":"1235",
"description":"description 1"
},
{
"product":"1325",
"description":"description 2"
},
...
]
和JavaScript代码
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item;
// Add the <option> element to the <datalist>.
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. datalist";
} else {
// An error occured :(
input.placeholder = "Couldn't load datalist options :(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading options...";
// Set up and make the request.
request.open('GET', 'myfile.json', true);
request.send();
国家处于&#34;加载选项&#34;并没有改变。如果我改变JSON,比如
[
"product",
"description"
]
然后它起作用,&#34;产品&#34;和&#34;描述&#34;显示为可能的选择..我必须在JavaScript中编辑以便仅显示元素product
?
答案 0 :(得分:1)
您正在尝试将选项值设置为对象:
option.value = item;
要仅使用product
成员,请明确执行此操作:
option.value = item.product;
您还可以将描述包含为可见选项文本:
option.text = item.description;
var dataList = document.getElementById('json-datalist');
var jsonOptions = [{
"product": "1235",
"description": "description 1"
}, {
"product": "1325",
"description": "description 2"
}];
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value = item.product;
option.text = item.description;
dataList.appendChild(option);
});
&#13;
<select name="" id="json-datalist">
</select>
&#13;