简体   繁体   English

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

[英]How to create list by importing txt file in javascript?

I have a department.txt file that contains departments: 我有一个包含department的department.txt文件:

Chemistry
Physics
Mathematics
Other

and i want to create a drop down list <select> by importing this file in my HTML. 我想通过在HTML中导入此文件来创建下拉列表<select> How can i do it using Javascript ? 我如何使用Javascript做到这一点? There are 50+ departments in file , so creating <option> for every department will not be a good idea. 文件中有50多个部门,因此为每个部门创建<option>并不是一个好主意。

To read txt file, you need to make an ajax call to department.txt and iterate departments like this: 要读取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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM