选项 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>