![](/img/trans.png)
[英]How to read a local text file to a local html and read the content to a two dimensional array for javascript?
[英]read from a local text file and update and updating the content in an html tag
我需要读取本地文本文件并使用文本文件的内容更新我的html页面。 我在嵌入式系统上工作时没有那么多浏览器支持。
但它给出了以下错误:
XMLHttpRequest cannot load file:///C:/Documents%20and%20Settings/aryas/Desktop/localtoken.txt. Cross origin requests are only supported for HTTP.
代码如下。
<script>
window.onload = function readTextFile()
{
console.log("Inside function");
var file = "localtoken.txt";
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
document.getElementById("token").innerHTML = allText;
}
}
}
rawFile.send(null);
}
</script>
将此文本文件放在与index.html相同的目录中。 在ajax请求中,您的路径看起来就像在您的网站上 - 'readfile.txt'
您需要将文件URL传递给XMLHttpRequest。
xmlhttp.open('GET', 'http://localhost/file.txt', false);
为此,您需要配置一个可以处理您的请求的网络服务器。 例如,您可以安装Apache服务器并将其启动并将file.txt部署到其中。 一旦浏览器向webserver发送了对file.txt的请求,webserver就会返回文件和您可以使用您在问题中提到的相同方法处理的响应。
简短的回答:你不能做你想做的事,就像你现在正在做的那样。 您必须在Web服务器中提供文件。 尝试LightHTTPD , Nginx或Mongoose
答案很长:从你得到的错误中,你必须打开index.html文件(带有脚本的文件),而不是从Web服务器提供它(为了确认这一点,让我问一下:浏览器中的URL是否启动用file://
?)。
正如类名所述, XMLHttpRequest
仅支持HTTP / HTTPS请求(blob URI正在开发中,如此处所述: http : //en.wikipedia.org/wiki/XMLHttpRequest )。
事实上,如果没有用户手动选择文件,您将无法从文件系统加载/保存文件,因为这是一个安全威胁(想象一下,您打开一个网站并加载您的C:
并将其发送到服务器,你想要一个网站吗?)。
要加载localtoken.txt
文件,请在轻巧的小型Web服务器中提供文件(当您在嵌入式系统上工作时)。 我在简短回答中建议的那些填写了这些要求,但从这个问题看来,似乎是猫鼬的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.