我有一个小的 html/javascript 网页,我想在浏览器中离线运行。
以同样的方式,页面可以包含图像或 css 文件并在离线时使用它,我想包含一个 3mb 的电子表格,javascript 将其读入二维数组,我希望有一些有用的东西在 IE8 和现代浏览器上。
C:\Folder\index.html
C:\Folder\code.js
C:\Folder\picture.png
C:\Folder\spreadsheet.csv
我在网上找到了很多方法,比如
<script src="jquery-csv.js"></script>
var table = $.csv.toArrays("spreadsheet.csv");
或
d3.text('spreadsheet.csv', function(error, _data){
var table = d3.csv.parseRows(_data);
});
或
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
但我往往会遇到同源策略错误,例如:
XMLHttpRequest cannot load file://data.txt. Received an invalid response. Origin 'null' is therefore not allowed access.
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.
我似乎无法让它们离线工作。我怎样才能做到这一点?
编辑:
我使用找到的 CSVToArray 函数设法使以下内容仅适用于 Firefox 上的文本文件 here ,对于这种大小的文件和一个隐藏的 iframe
来说,这是相当缓慢的。
最终,如果它能够在 IE8 上运行,并且我使用的是 csv 而不是 txt 文件,那将是更好的选择,但至少这是一个开始。
<iframe style="display:none;" id='text' src = 'file.txt' onload='read_text_file()'>
</iframe>
<script type="text/javascript" >
function read_text_file() {
var text = document.getElementById('text').contentDocument.body.firstChild.innerHTML;
var table = CSVToArray(text);
}
对于 IE8 我设法让它在小范围内工作,但是对于 3mb 的文件,它偶尔会导致浏览器崩溃,并且总是会向用户发出大量警告消息,提示 activex 是正在使用,并发出一波警告,提示该脚本会降低计算机速度。
window.onLoad = readFileInIE("file.csv");
function readFileInIE(filePath) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, true);
var text = file.ReadAll();
var table = CSVToArray(text);
file.Close();
return fileContent;
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
最佳答案
这在 IE8 中可能不起作用,但 HTML5 API 对此非常有用。只需使用:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = //format you'd like to recieve;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
// apply magic here
}
reader.readAsText(file);
}
else
{
fileDisplayArea.innerText ="Sorry matey, can't help you with that filetype."
}
});
}
然后,一个看起来像这样的简单 .html 文件就可以解决问题:
<html lang="en">
<head>
<script src="script.js"></script>
</head>
<body>
<div id="page-wrapper">
<div>
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"></pre> //display any output here
</div>
</body>
</html>
关于javascript - 如何在离线时将 txt/csv 文件加载到 javascript 字符串/数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346008/