Javascript 通过客户端javascript读取txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8137225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:50:29  来源:igfitidea点击:

read txt file via client javascript

javascript

提问by Elad

I'm new to javascript and trying to open a txt file into var and then inject it to html div... I tried to use fopen but I didn't succeed.

我是 javascript 新手,并试图将 txt 文件打开到 var 中,然后将其注入到 html div 中...我尝试使用 fopen 但我没有成功。

<script type="text/javascript">
file = fopen(getScriptPath("info.txt"), 0);


file_length = flength(file);
var content = fread(file,file_length);
var div = document.getElementById("myDiv");
//alert(div);
div.innerHTML = "";
div.innerHTML = content;
</script>

采纳答案by badfur

abandoned question:

放弃的问题:

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","YOUR_FILE.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;

by Freek8

由 Freek8

回答by Freek8

Although it says xml request this works perfectly fine for txt files too (server and client side).

虽然它说 xml 请求,但这也适用于 txt 文件(服务器和客户端)。

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","YOUR_FILE.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;

回答by Dennis

JavaScript has none of the functions you are trying to use.

JavaScript 没有您尝试使用的任何功能。

To read files on the server in JavaScript, you can use XMLHttpRequest.

要在 JavaScript 中读取服务器上的文件,您可以使用XMLHttpRequest

There is no easy way to read files on the client machine.

没有简单的方法可以读取客户端计算机上的文件。

回答by Bikonja

For security reasons, Javascript is made so you can not do this. However, a person has made a workaround which may work and posted it here.

出于安全原因,Javascript 已制作,因此您无法执行此操作。但是,有人提出了一个可行的解决方法并将其张贴在此处

Ok, I realize, it only works for files that are publicly accessbile on the server, which I believe is not what you want to do. Still, if you do find a way, it will be a hack like this, but it could also be fixed to not work at any time.

好的,我意识到,它仅适用于服务器上可公开访问的文件,我认为这不是您想要做的。尽管如此,如果你确实找到了一种方法,这将是一个像这样的黑客,但它也可以被修复为在任何时候都不起作用。