从本地文件

时间:2016-04-28 11:58:25

标签: javascript jquery file readfile

我有一些Javascript代码来读取文件。我在浏览器中从本地文件系统打开此文件:

var rawFile = new XMLHttpRequest();
rawFile.open("GET", "test.txt", false);
rawFile.onreadystatechange = function () {
    if(rawFile.readyState === 4) {
        if(rawFile.status === 200 || rawFile.status == 0) {
            findWord(rawFile.responseText.split("\n"));
        }
    }
}
rawFile.send(null);

这很好用,但在Chrome中已弃用。在发现之后,我尝试使用$.get(),如此:

$.get("test.txt", function(result) {
    alert(result);
});

但它甚至没有警觉。

有没有办法在Chrome和Firefox中读取此文件?请注意,我不想使用任何类型的<input type="file">,并且必须在文件的行数组中返回文本数据。

使用$.get()$.ajax()时,Chrome收到警告并显示错误。

错误:

  

index.html:36 XMLHttpRequest无法加载file:/// C:/Users/mz/Dropbox/Shubs/test.txt。交叉源请求仅支持协议方案:http,数据,chrome,chrome-extension,https,chrome-extension-resource。

我也没有在服务器上运行。因此localhost在这种情况下不起作用。

2 个答案:

答案 0 :(得分:3)

你得到了:

  

交叉源请求仅支持协议方案:http,   数据,chrome,chrome-extension,https,chrome-extension-resource错误

因为您使用 file:// C:/ 加载文件,因为它们不是 http,所以它仍然是错误消息: // 所以我有两个建议的解决方案:

  1. 要么从服务器(php,nodejs)发送文件并将其捕获 客户(ajax)
  2. 或者您使用js文件阅读器阅读文本文件

答案 1 :(得分:-1)

你试过这个吗?

$.ajax({
            url: "test.txt",
            async: false,
            success: function (data){
                console.log(data);
            }
        });

然后检查浏览器的控制台。