gpt4 book ai didi

javascript - 将 JSON 文件加载到数据列表输入

转载 作者:行者123 更新时间:2023-12-03 08:12:19 25 4
gpt4 key购买 nike

我想从 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();

状态处于“正在加载选项”并且不会改变。如果我改变 JSON,比如

[ 
"product",
"description"
]

然后它就起作用了,“产品”和“描述”显示为可能的选择。我必须在 JavaScript 中编辑什么才能仅显示元素 product

最佳答案

您正在尝试将选项值设置为对象:

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);
});
<select name="" id="json-datalist">
</select>

关于javascript - 将 JSON 文件加载到数据列表输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34089643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com