【问题标题】:Javascript to read local file works on windows but not on linux用于读取本地文件的 Javascript 适用于 Windows 但不适用于 linux
【发布时间】:2015-02-04 13:59:35
【问题描述】:

我有一个小的 Javascript,它应该读取本地文本文件的内容并将其显示在浏览器屏幕上。 它适用于具有当前 Firefox 的 Windows 7,但不适用于具有当前 Firefox 或 chrome 的 fedroa 20。 代码如下:

<h1>View file content</h1>

<script>
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

function read_status()
{
    readTextFile('file:///tmp/status.txt');
}

</script>

<input id="clickMe" type="button" value="Current status" onclick="read_status(); " />

这是为什么?我该如何解决?

【问题讨论】:

  • 如何在 Linux 上获取文件。像那样file:///tmp/status.txt ?
  • 只要明白你不应该依赖这种行为。我很惊讶 Firefox 允许这个开箱即用(或者你改变了什么?)本地文件系统访问是 JavaScript 的过去。使用服务器端技术为您从文件系统中读取文件内容。您仍然可以使用 AJAX 向服务器发出请求,它只是通过 URL(例如 http://localhost/myapp/pleasegetmefile.php?path=/tmp/statust.txt - 但即使这样也很危险,因为您可能会请求敏感文件)。
  • 我还想知道这是否可能是一个默认的安全设置,它因操作系统而异。我没有有意识地改变任何设置。由本地脚本创建 - 我希望它非常简单。我可以实现一个小型本地 Web 服务器,但这对我的意图来说似乎有点过头了。
  • 您可以将对象与文本数据一起使用。这是example。如果您需要从文件系统的另一部分提供文件,那么您肯定需要服务器提供所需的文件夹(或单个文件)。
  • 我可以让对象自动重新加载吗?理想情况下,它会监视文件的更改,但定期重新加载也可以。

标签: javascript linux window


【解决方案1】:

所以对于我想要的,答案真的很简单,不需要java脚本,只需要普通的html:

<h1>Status </h1>

<meta http-equiv="refresh" content="1" > 
<object width="100%" height="100%" type="text/plain" data="/tmp/status.txt" border="0" >

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多