如何通过导入javascript中的txt文件来创建列表

How to create list by importing txt file in javascript?

本文关键字:文件 创建 列表 txt 中的 何通过 导入 javascript      更新时间:2023-09-26

我有一个department.txt文件,其中包含部门:

Chemistry
Physics
Mathematics
Other

我想通过在我的HTML中导入这个文件来创建一个下拉列表CCD_ 2。如何使用Javascript?文件中有50多个部门,所以为每个部门创建<option>不是一个好主意。

要读取txt文件,您需要对department.txt进行ajax调用,并迭代如下部门:

function readFile() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var res = xhttp.responseText;
      res = res.split(''n');
      var html = '<select name="department">';
      res.forEach(function(item) {
        html += '<option value="' + item + '">' + item + '</option>';
      });
      html += '</select>';
      document.body.innerHTML = html;
    }
  };
  xhttp.open("GET", "department.txt", true);
  xhttp.send();
}
readFile();