简体   繁体   English

使用 Javascript 单击按钮读取并显示文本文件内容

[英]Read and display the text file contents upon click of button using Javascript

On click of a button called result , I want to read and display a text file (which is present in my local drive location say: C:\\test.txt ) using Javascript function and display the test.txt file contents in a HTML text area.单击名为result的按钮后,我想使用 Javascript 函数读取并显示一个文本文件(存在于我的本地驱动器位置,例如: C:\\test.txt )并以 HTML 文本显示 test.txt 文件内容区域。

I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?我是 Javascript 的新手,有人可以建议 Javascript 函数的代码来读取和显示 .txt 文件的内容吗?

An Ajax request to a local file will fail for security reasons.出于安全原因,对本地文件的 Ajax 请求将失败。

Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker.想象一下,一个网站按照您的要求访问您计算机上的文件,但没有让您知道,并将内容发送给黑客。 You would not want that, and browser makers took care of that to protect your security!你不会想要这样的,浏览器制造商会照顾到这一点来保护你的安全!

To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself .要读取硬盘驱动器上文件的内容,您需要有一个<input type="file">让用户自己选择文件 You don't need to upload it.你不需要上传它。 You can do it this way :你可以这样做:

<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var result = document.getElementById("result");

  reader.onload = function(event) {
    result.innerHTML = event.target.result;
  };

  reader.readAsText(selectedFile);
}

JS Fiddle JS小提琴

Using $.ajax() function: http://api.jquery.com/jQuery.ajax/使用 $.ajax() 函数: http : //api.jquery.com/jQuery.ajax/

$(function(){
    $.ajax({
        url: "pathToYourFile",
        async: false,   // asynchronous request? (synchronous requests are discouraged...)
        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
        dataType: "text",  // jQuery will infer this, but you can set explicitly
        success: function( data, textStatus, jqXHR ) {
            var resourceContent = data; // can be a global variable too...
            // process the content...
        }
    });
});

As You've mentionned HTML, I assume you want to do this in a browser;正如您提到的 HTML,我假设您想在浏览器中执行此操作; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.那么在浏览器中访问本地文件的唯一方法是使用文件 API,并且只能通过用户的操作来获取文件,例如在 <input type='file'> 元素中选择文件或拖放文件在您的页面中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM