有谁知道如何使用 JS 从服务器端文件读取数据的教程?当我用谷歌搜索时,我似乎找不到任何主题。我尝试使用但它似乎不起作用。我只想从文件中读取一些数据以显示在页面上。这可能吗?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
最佳答案
为此,您必须使用称为 AJAX 的方法从服务器检索文件。
我会研究 JavaScript 库,例如 Mootools 和 jQuery。它们使 AJAX 的使用变得非常简单。
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
如果您将其上传到 test.csv 驻留在您的网络服务器上的目录并加载页面,您应该会看到 test.csv 的内容出现在定义的文本区域中。
关于javascript - 使用 Javascript 读取服务器端文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567369/