0
我有一个department.txt
文件,其中包含部门:如何通过在JavaScript中导入txt文件来创建列表?
Chemistry
Physics
Mathematics
Other
,我想通过我的HTML导入此文件来创建一个下拉列表<select>
。我怎样才能使用Javascript
? 档案中有50多个部门,因此为每个部门创建<option>
不是一个好主意。
我有一个department.txt
文件,其中包含部门:如何通过在JavaScript中导入txt文件来创建列表?
Chemistry
Physics
Mathematics
Other
,我想通过我的HTML导入此文件来创建一个下拉列表<select>
。我怎样才能使用Javascript
? 档案中有50多个部门,因此为每个部门创建<option>
不是一个好主意。
要阅读
txt
文件,你需要做一个ajax
调用department.txt
和迭代部门是这样的:
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();
非常感谢你爵士:)这是行得通的 –
有你试一下? –
据我所知,JavaScript不会让你访问文件系统,所以你将无法用JS打开department.txt。 –
@ShailendraSharma yes。我已经尝试使用php来导入文件并在javascript中创建列表。这是行不通的。 –