javascript - 使用javascript读取本地文本文件

标签 javascript jquery html

我试图通过javascript和jquery读取存储在同一目录中的HTML页面textread.html中的test.txt。但我收到以下错误:

方法1 jQuery方法

<小时/>

jQuery 错误: 请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问源“null”。

<小时/>

jQuery: `

$.getJSON('test.txt', function(data) {
    console.log(data);
});

`

<小时/>

方法2 javascript方法

<小时/>

javascript 错误:仅 HTTP 支持跨源请求。

<小时/>

JavaScript:

`

if (xmlhttp != null)    {
    xmlhttp.open("GET","test.txt",false); // the false makes this synchronous!
    xmlhttp.send();
    var text = xmlhttp.responseText;
}

`

<小时/>

我也尝试过替代代码

我没有托管此应用程序,因为我将使用 PhoneGap 作为移动应用程序来部署它。

请为我提供在这种情况下读取文件的解决方案。 作为替代解决方案,建议使用 HTML5 FileReader 吗?

最佳答案

如果您使用 HTML 5,我发现了一个非常好的教程:

Reading Files using HTML 5

HTML:

<div id="page-wrapper">

   <h1>Text File Reader</h1>
   <div>
      Select a text file: 
      <input type="file" id="fileInput">
   </div>
   <pre id="fileDisplayArea"><pre>

</div>

JavaScript:

window.onload = function() {
   var fileInput = document.getElementById('fileInput');
   var fileDisplayArea = document.getElementById('fileDisplayArea');

   fileInput.addEventListener('change', function(e) {
      var file = fileInput.files[0];
      var textType = /text.*/;

      if (file.type.match(textType)) {
         var reader = new FileReader();

         reader.onload = function(e) {
            fileDisplayArea.innerText = reader.result;
         }

         reader.readAsText(file);   
      } else {
         fileDisplayArea.innerText = "File not supported!"
      }
   });
}

关于javascript - 使用javascript读取本地文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069147/

相关文章:

javascript - 可以修改 jQuery ajax 请求中的 cookie 值吗?

javascript - 将浏览器中加载的样式表合并并保存到一个文件中

javascript - 如何在 jQuery 上正确重写 JS 函数

javascript - 使用 JQuery Ajax 提交表单不在服务器中工作,但在本地主机中工作 codeigniter

javascript - 延迟超链接

html - div有不同的高度

javascript - AngularJS 中的一种 HTML 绑定(bind)方式

javascript - 集成 Netbeans、symfony 和 dart

javascript - .on 如何为 $(document) 工作

javascript - JSON 到 JavaScript 对象 #text 属性