文件在html中读取

时间:2015-02-23 02:54:54

标签: javascript html html5 filereader

我想知道除了文件读取api和XMLHttprequest()之外是否有任何方法来读取/加载支持几乎所有Web浏览器的文本文件。
我没有使用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>

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

2 个答案:

答案 0 :(得分:1)

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

您自己(开发)机器的替代品:
对于chrome,您可以允许XMLHttpRequest使用以下方法访问其他文件中的文件:
--allow-file-access-from-files
这至少比使用--disable-web-security

更安全

另一个快速解决方案是&#34;微小&#34;:https://www.ritlabs.com/en/products/tinyweb/download.php
我喜欢它,因为它是 !!然后(通过环回ip或本地机器ip或主机名通过主机文件)我解决这些限制,清除cookie /沙箱/本地存储功能的路径以及你试图解决的问题。

然而,这对简单的可分发的html / javascript-app没有帮助...正如你所指出的那样,它目前是一个“赢得”修复&#34;用于镀铬。

答案 1 :(得分:0)

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

var text = "ORIGINAL TEXT" 

将文件添加为脚本标记。