2015-11-06 61 views
0

我有一个department.txt文件,其中包含部门:如何通过在JavaScript中导入txt文件来创建列表?

Chemistry 
Physics 
Mathematics 
Other 

,我想通过我的HTML导入此文件来创建一个下拉列表<select>。我怎样才能使用Javascript? 档案中有50多个部门,因此为每个部门创建<option>不是一个好主意。

+0

有你试一下? –

+0

据我所知,JavaScript不会让你访问文件系统,所以你将无法用JS打开department.txt。 –

+0

@ShailendraSharma yes。我已经尝试使用php来导入文件并在javascript中创建列表。这是行不通的。 –

回答

1

要阅读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(); 
+1

非常感谢你爵士:)这是行得通的 –

相关问题