我试图通过创建一个函数来实现一个简单的文本文件阅读器,该函数接受文件的路径并将每行文本转换为字符数组,但它不起作用。
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
var allText = rawFile.responseText;
document.getElementById("textSection").innerHTML = allText;
}
}
rawFile.send();
}
这里出了什么问题?
这似乎仍然不工作后,改变了代码一点点从以前的修订,现在它给我一个XMLHttpRequest异常101。
我已经在Firefox上测试过了,它可以工作,但在谷歌Chrome中,它不会工作,它一直给我一个101例外。我怎么能让它不仅在Firefox上工作,而且在其他浏览器(尤其是Chrome)上工作?
在js(data.js) load中获取本地文件数据:
function loadMyFile(){
console.log("ut:"+unixTimeSec());
loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
var mA_=mSdata.split("\n");
console.log(mA_.length);
}
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
return Math.round( (new Date()).getTime()/1000);
}
data.js文件如下:
var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});
dynamic unixTime queryString阻止缓存。
AJ在网站http://.工作
function readTextFile(file) {
var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
rawFile.open("GET", file, false); // open with method GET the file with the link file , false (synchronous)
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
{
if(rawFile.status === 200) // status 200: "OK"
{
var allText = rawFile.responseText; // Returns the response data as a string
console.log(allText); // display text on the console
}
}
}
rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}
readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path
-从javascript读取文件文本
-控制台日志文本从文件使用javascript -谷歌chrome和mozilla firefox在我的情况下,我有这样的文件结构:
console.log结果:
您需要检查状态0(当使用XMLHttpRequest在本地加载文件时,您不会返回状态,因为它不是来自web服务器)
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
在你的文件名中指定file://:
readTextFile("file:///C:/your/path/to/file.txt");