[英]Javascript read text file from current directory
如何在不使用 jquery 的情況下使用 javascript 從當前目錄讀取文本文件 (text1.txt)。 我嘗試了以下代碼。
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
FileReader API 通常用於讀取通過<input type="file">
選擇的<input type="file">
。 它無法讀取任意文件。 readAsText
方法期望接收 Blob 或 File 對象,而不是包含文件名的字符串。
要讀取 HTML 文檔的同級文件,請使用XMLHttpRequest 。 如果您通過 HTTP(S) 加載文檔,這將可靠地工作。 如果您使用的是本地 HTML 文檔(通過file:
URI),那么許多瀏覽器中的安全限制將阻止它工作(並且您應該運行本地 Web 服務器)。
選項 A,您的用例阻止您使用 http 或 php 服務器。 您可以使用腳本包含將本地內容作為變量包含在 javascript 中。 如果您在本地打開頁面,作為目錄中的文件,這是在網頁中包含本地內容的唯一方法。
要包含本地內容,請將其放在其他腳本標簽上方:
<script src="text1.txt"></script>
並編輯您的 text1.txt 文件,以便將所有內容分配給一個變量:
gbl_text=`...contents of my text file...
...more contents...
...and so on....
`
例如,您可以使用腳本來創建此包含文件(使用波浪號 ~ 鍵下方的 ` 勾號):
echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt
然后根據需要在 javascript 中使用 gbl_text 變量...
function dosomething()
{
if (typeof(gbl_text)=='undefined'){
setTimeout('dosomething()',500) //call back until defined
}else{
console.log(gbl_text)
}
}
選項 B,您的用例將允許您使用 php-cli 內置服務器。 如果您能夠運行 php-cli,您可以在內置的 php 網絡服務器上打開頁面,並通過 php 調用讀取和寫入本地內容。 要在 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
因此,不是將 html 作為文件打開,而是作為 http 網頁打開:
firefox http://localhost:8000/mypage.html
#or browser of choice
現在本地網頁由具有 php 支持的實際(本地)http 服務器提供服務,您可以使用它來操作本地文件。
這是一個簡單的例子,展示了如何使用 jQuery 和 php 讀取和寫入本地文件。 下載 jQuery(請參閱 jQuery.com)並將其包含在您的 html 文件中。
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;
}
?>
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>
請區分2種讀取文件:
<input type="file">
制作一個小小的 iframe。 在那里加載文件。 用 iframe.innerHTML 閱讀它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.