[英]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 anajax
call todepartment.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.