我尝试从服务器读取本地文件。我一直在“谷歌搜索”这个话题一段时间,有人说这是不可能的,其他人说可以做到。在这次搜索中,我发现了这个脚本:
Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk, this is an easy way to read in a data file. Writing out is more complicated and requires either an ActiveX object (IE) or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
Return a cross-browser xmlhttp request object
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
但是不知道怎么用,回调函数应该怎么看?您能否提供使用这些功能的示例代码?
最佳答案
能够从您的浏览器读取本地文件将是对安全性的重大破坏 - 我不喜欢我访问的任何网站能够在我的浏览器中运行可以从我的硬盘驱动器读取文件的代码的想法。通常,ajax 请求仅限于页面源自的域。 (但是,您可以使用 JSONP 等技术在一定程度上解决此问题。)即使页面源自本地文件系统,大多数浏览器也不会让您读取本地文件。
提到的其他方法应该允许您从域(即使它是 localhost)读取文件,但不能直接从文件系统读取文件。
关于Javascript,如何读取本地文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511970/