html 中的文件读取

File reading in html

我想知道除了读取 api 和 XMLHttprequest() 到 read/load 支持几乎所有网络浏览器的文本文件外,是否还有其他方法。
我没有使用 xmlhttprequest(),因为它在少数浏览器中不能 运行,例如 chrome(因为它有一个错误)you may find it here 我想知道这方面的纯 javascript/html 方法,并想避免使用 php 和 django 脚本。

我尝试了以下 xmlhttprequest 方法

<!doctype html>
<html>
<head>
    <body>  
    <script>
    if (window.File && window.FileReader && window.FileList && winddow.Blob) { //alert('Great success! All the File APIs are supported.');
}
    else {
  alert('The File APIs are not fully supported in this browser.');
}
var req = new XMLHttpRequest();
req.open('GET', 'text.txt');
req.onreadystatechange = function() {
  if (req.readyState == 4) {
    if (req.status == 200) {
      var lines = req.responseText.split(/\n/g);
      lines.forEach(function(line, i) {
        alert(line);
      });
    } else {
       (alert("please update your browser,this webpage doesnt have     support for your browser"))
    }
  }
}
req.send();
    </script>
    </body>
</head>
</html>

这 运行s 在 firefox 35.0.1
但是当我尝试在 chrome 中使用它时它不起作用
但是,如果我删除条件 if(req.status==200),那么我会收到一个没有文本的警报。

用户控制的文件-api 和可编写脚本的 XMLHTTPRequest 几乎是唯一的选择。或者,您可能会幸运地使用 java 或 flash 或 silverlight(等)方法(我现在将其留给其他答案)。

您自己(开发)机器的备选方案:
对于 chrome,您可以允许 XMLHttpRequest 使用以下方式从其他文件访问文件:
--allow-file-access-from-files
这至少比使用更安全:--disable-web-security

另一个快速解决方案是 "tiny":https://www.ritlabs.com/en/products/tinyweb/download.php
我喜欢它,因为它!!然后(通过环回 ip 或本地机器 ip 或通过主机文件的主机名)我解决了这些限制,清除了 cookie/sandbox/local-storage 功能的路径和你试图解决的问题。

然而,这对简单的可分发 html/javascript-app 没有帮助...正如您所指出的,它目前是 chrome 的 "won't-fix"。

如果您有权访问该文本文件,您可以将其编辑为

var text = "ORIGINAL TEXT" 

并将文件添加为脚本标签。