简体   繁体   English

Javascript从当前目录读取文本文件

[英]Javascript read text file from current directory

How to read text file (text1.txt) from current directory using javascript without jquery.如何在不使用 jquery 的情况下使用 javascript 从当前目录读取文本文件 (text1.txt)。 I tried the following code.我尝试了以下代码。

var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);

The FileReader API is usually used to read files selected via the an <input type="file"> . FileReader API 通常用于读取通过<input type="file">选择的<input type="file"> It cannot read arbitrary files.它无法读取任意文件。 The readAsText method expects to receive with a Blob or a File object, not a string containing a file name. readAsText方法期望接收 Blob 或 File 对象,而不是包含文件名的字符串。

To read files that are siblings of the HTML document, use XMLHttpRequest .要读取 HTML 文档的同级文件,请使用XMLHttpRequest This will reliably work if you load the document over HTTP(S).如果您通过 HTTP(S) 加载文档,这将可靠地工作。 If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).如果您使用的是本地 HTML 文档(通过file: URI),那么许多浏览器中的安全限制将阻止它工作(并且您应该运行本地 Web 服务器)。

Option A, Your use-case prevents you from using an http or php server.选项 A,您的用例阻止您使用 http 或 php 服务器。 You can include local content in your javascript as a variable using a script include.您可以使用脚本包含将本地内容作为变量包含在 javascript 中。 If you are opening the page locally, as a file from a directory, this is the only way to include local content in the web page.如果您在本地打开页面,作为目录中的文件,这是在网页中包含本地内容的唯一方法。

To include local content, put this above your other script tag:要包含本地内容,请将其放在其他脚本标签上方:

<script src="text1.txt"></script>

and edit your text1.txt file so it assigns all the content to a variable:并编辑您的 text1.txt 文件,以便将所有内容分配给一个变量:

gbl_text=`...contents of my text file...
...more contents...
...and so on....   
`

You can use a script to create this include file, for example (use the ` tick mark below the tilde ~ key):例如,您可以使用脚本来创建此包含文件(使用波浪号 ~ 键下方的 ` 勾号):

echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt

Then use the gbl_text variable in your javascript as needed...然后根据需要在 javascript 中使用 gbl_text 变量...

function dosomething()
{
  if (typeof(gbl_text)=='undefined'){
    setTimeout('dosomething()',500)  //call back until defined
  }else{
    console.log(gbl_text)
  }
}

Option B, Your use-case would allow you to use the php-cli built-in server.选项 B,您的用例将允许您使用 php-cli 内置服务器。 If you are able to run php-cli, you can open the page on the built-in php webserver, and read and write local content with a php call.如果您能够运行 php-cli,您可以在内置的 php 网络服务器上打开页面,并通过 php 调用读取和写入本地内容。 To install and use php on linux,要在 linux 上安装和使用 php,

sudo apt install php7.0-cli
#To use the php built-in webserver, run:
php -S localhost:8000 -t /path/to/your/content

So, instead of opening your html as a file, you would open as an http web page:因此,不是将 html 作为文件打开,而是作为 http 网页打开:

firefox http://localhost:8000/mypage.html
#or browser of choice

Now the local webpage is being served by an actual (local) http server with php support, and you can manipulate local files with it.现在本地网页由具有 php 支持的实际(本地)http 服务器提供服务,您可以使用它来操作本地文件。

Here is simple example showing how to read and write to a local file using jQuery and php.这是一个简单的例子,展示了如何使用 jQuery 和 php 读取和写入本地文件。 Download and include jQuery (see jQuery.com) in your html file.下载 jQuery(请参阅 jQuery.com)并将其包含在您的 html 文件中。

Contents of dofile.php: dofile.php 的内容:

<?php 
$dowhat  = $_REQUEST['dowhat'];
  if ($dowhat=='save'){
    $myvar = $_REQUEST['myvar'];
    file_put_contents('myfile', $myvar); 
  }elseif($dowhat=='read'){
    $myvar=file_get_contents('myfile');
    echo $myvar; 
  }
?> 

Contents of mypage.html: mypage.html 的内容:

<script src='jquery-3.2.1.js';></script>
<!--make sure the filename matches the jQuery you use-->

<script>
function savevar(){
  var myvar=document.getElementById('mytxt').value
  var path="dofile.php?dowhat=save&myvar="+myvar 
  $.get(path, function(data){
    console.log("saved ...\n"+myvar)
    alert("saved ...\n"+myvar)
  });
}

function clearbox(){
  document.getElementById('mytxt').value='reading file...'
  setTimeout('getvar()',1000)
}

function getvar(){
  var path="dofile.php?dowhat=read"
  $.get(path, function(data){
    console.log(data);
    document.getElementById('mytxt').value=data
    /*do other things with data here*/;
  });
}
</script>

<html>
Type something in the text box.<br>
Use the Read and Write buttons to verify <br>
text is saved and read back.<br> 
<input id='mytxt' value='type text here' onclick=document.getElementById('mytxt').value=''><br>
<input type='button' value='Save' onclick=savevar() ><input type='button' value='Read' onclick=clearbox() >

</html>

Please distinguish 2 kinds of reading files:请区分2种读取文件:

  • reading "from internet" - use XMLHttpRequest to read any kind of file读取“从互联网” - 使用XMLHttpRequest读取任何类型的文件
  • reading "from client" - use FileReader or <input type="file">读取“从客户端” - 使用 FileReader 或<input type="file">

make a tiny iframe.制作一个小小的 iframe。 load the file there.在那里加载文件。 read it with iframe.innerHTML用 iframe.innerHTML 阅读它

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

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