从本地javascript文件读取本地文本文件

Reading a local text file from a local javascript file?

本文关键字:文件 文本 读取 javascript      更新时间:2023-09-26

我正在使用以下代码从本地Javascript文件读取本地文本文件,但它不起作用:

var txtFile = new XMLHttpRequest();
txtFile.open('GET', fileLocation, true);

我得到的错误:

XMLHttpRequest cannot load file:///C:/File.txt. Cross origin requests are only supported for HTTP.

有什么想法吗?

您不能从javascript访问本地资源,你应该把这个文件放在你的网站上,并尝试通过fileLocation访问它,比如http://mywebsite/File.txt

看看这个:

var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
 document.f1.t1.value='Reading in progress...';
 document.ReadURL.readFile(theLocation);
 setTimeout("showFileContent()",100);
}
function showFileContent() {
 if (document.ReadURL.finished==0) {
  setTimeout("showFileContent()",100);
  return;
 }
 fileContent=document.ReadURL.fileContent;
 document.form1.textarea1.value=fileContent;
}