如何在离线时将 txt/csv 文件加载到 javascript 字符串/数组中

Cha*_*ton 5 javascript csv arrays offline

我有一个小的 html/javascript 网页,我想在浏览器中离线运行。

以同样的方式,页面可以包含一个图像或一个 css 文件并在离线时使用它,我想包含一个 3mb 的电子表格,javascript 将它读入一个二维数组,我希望有一些可以在 IE8 上工作的东西以及现代浏览器。

C:\Folder\index.html
C:\Folder\code.js
C:\Folder\picture.png
C:\Folder\spreadsheet.csv
Run Code Online (Sandbox Code Playgroud)

我在网上找到了多种方法,例如

<script src="jquery-csv.js"></script>
var table = $.csv.toArrays("spreadsheet.csv");
Run Code Online (Sandbox Code Playgroud)

或者

d3.text('spreadsheet.csv', function(error, _data){
            var table = d3.csv.parseRows(_data);
        });
Run Code Online (Sandbox Code Playgroud)

或者

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});
Run Code Online (Sandbox Code Playgroud)

但我倾向于得到同源策略错误,例如:

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. 
Run Code Online (Sandbox Code Playgroud)

我似乎无法让这些离线工作。我怎么能做到这一点?

编辑:

我设法使用此处找到的 CSVToArray 函数使以下内容仅适用于Firefox上的文本文件,该函数对于这种大小的文件和隐藏的.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); 
}
Run Code Online (Sandbox Code Playgroud)

对于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"'); 
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rya*_*n B 0

不太清楚你想做什么。

使用 jQuery 可以修改 DOM 中发生的事件。使用此功能,您可以在完成更改后保存源代码。然后,您需要用保存的代码替换当前的源代码,以便在下次打开页面时使用更改。然而,这将是一个非常费力的过程,并且可能有许多更好的方法来完成您想要做的事情,具体取决于它是什么。

另外,关于 Shota 的帖子。除非您有后台运行的服务器,否则您无法使用 AJAX。如果您决定在服务器上设置系统,有多种选项可以实现您的需求。