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

Load JSON file to datalist input

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

状态为 "Loading options",没有变化。如果我改变 JSON,比如

[ 
   "product",
   "description"
]

然后它起作用,"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>