简体   繁体   中英

reading a text file line by line only with javascript

I don't want solution using Node.js, FileReader, or whatever else exept javascript! Developing the html page, I encountered a problem as follows: I get accurate results with this procedure, unfortunately the procedure remembers result of the first login page. Whatever text file in the meantime change the content, the procedure returns the first result. Can someone give advice!

var filePath = "../../dir/sub dir/text_file.txt";
function getBackData(filePath){
    var axd, i, artx, txli, tdr;
    if(window.XMLHttpRequest){
        axd = new XMLHttpRequest();
    }else{
        axd = new ActiveXObject("Microsoft.XMLHTTP");
    }
    axd.open('GET', filePath, true);
    axd.onreadystatechange = function(){
        if(axd.readyState == 4 && axd.status == 200){
            artx = axd.responseText;
            txli = artx.split("\n"); 
            for(i = 0; i < txli.length; i++){
                alert(txli[i]);
            }
        }
    }
    axd.send(null);
}

This is probably because the browser cache it. If you send a parameter which is almost always different like timestamp, you can disable the cache. Or you can try to use POST, since post request are never cached.

You could try : axd setRequestHeader('Cache-Control', 'no-cache');

Or try: axd.open('GET', filePath+'?_=' + new Date().getTime()), true); This will prevent your server from using the cash, because each request is different.

You are not allowed to request local files directly with ajax - you need a server to serve them. The browser is sandboxed and cannot generally open local files. This is a security measure - imagine what would happen if any website was allowed to open your files!

There are ways to set up a simple server for your images, like http-server . This allows you to serve files directly off a chosen directory, like so:

npm install -g http-server
http-server path-to-text-files/

Then you can request the files normally with ajax, at a path relative to the one your server is serving, like so:

url = "/dir/subdir/text-file.txt";
...
ajax.open('GET', url, true);
...
ajax.send(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM