读取本地文件的实现
方案一:用 Ajax 请求本地文件
使用该方法读取本地文件时,必须开启本地服务器,并将文件放在服务器目录下。
function readTextFile(fileName){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", fileName, false); rawFile.onreadystatechange = function(){ if(rawFile.readyState === 4){ if(rawFile.status === 200 || rawFile.status == 0){ var allText = rawFile.responseText; alert(allText); } } } rawFile.send(null); } readTextFile("http://localhost/readFile/text.txt");
不过,该方法,会抛出一个警告:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.(翻译过来就是:不推荐使用主线程上的同步XMLHttpRequest,因为它会对最终用户体验造成不利影响。)
方案二:用 FileReader 读取本地文件
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/203863.html原文链接:https://javaforall.net
