[英]Use javascript to open and parse a file without server
Ok, I have a webpage that will run locally, every hour it needs to read a csv "output.csv" and put its contents into a table. 好的,我有一个将在本地运行的网页,每小时需要读取一个csv“output.csv”并将其内容放入一个表中。 The output.csv is generated from a local program automatically.
output.csv自动从本地程序生成。 The goal being an internal status board.
目标是内部状态委员会。
The only thing I can't seem to figure out is, without a server or xmlrequst how do I load a plaintext into javascript? 我唯一无法弄清楚的是,没有服务器或xmlrequst如何将明文加载到javascript中? (the rest of it should be easy)
(其余部分应该很简单)
This is the code that I've tried: 这是我尝试过的代码:
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText("output.csv");
EDIT: 编辑:
I've read that using this option "--allow-file-access-from-files" will override the settings and allow me to read local files from chrome. 我已经读过使用此选项“--allow-file-access-from-files”将覆盖设置并允许我从chrome读取本地文件。 I'm sure there is a way.
我确信有办法。
Ok, I found an answer! 好的,我找到了答案!
Javascript: 使用Javascript:
$(document).ready(function(){
$.get("output.csv", function( my_var ) {
alert(my_var)
});
});
Chrome: "chrome.exe --user-data-dir=c:\\temp --allow-file-access-from-files --incognito """ & currentDirectory & "index.html""" Chrome: “chrome.exe --user-data-dir = c:\\ temp --allow-file-access-from-files --incognito”“”&currentDirectory&“index.html”“”
The problem is, that you are running JavaScript, that is running in the browser and for security reasons it cannot access any file from your computer. 问题是,您正在运行JavaScript,它在浏览器中运行,出于安全考虑,它无法访问您计算机中的任何文件。 So if you are willing to stick with JavaScript just start a server (eg SimpleHttpServer or Node.js ) which will supply the file to your code.
因此,如果您愿意坚持使用JavaScript,只需启动一个服务器(例如SimpleHttpServer或Node.js ),它将为您的代码提供文件。
Otherwise you will need to ask the user explicitly to "upload" your csv
to the webpage - even though it is offline and living in his browser. 否则,您需要明确要求用户将您的
csv
“上传”到网页 - 即使它处于脱机状态并且仍然在他的浏览器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.