3

I have this function to read a text file from a specific location:

<html>
  <head>
    <script>
      function readTextFile(file){
        var out_text=''
        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;
              out_text=allText;
            }
          }
        }
        rawFile.send(null);
        return out_text;
      }
    </script>
  </head>
  <body>
    <div id="file_txt"></div>
    <script>
      txt = readTextFile('http://arbsq.net/dchampolu/champolu_data.txt');
      document.getElementById("file_txt").innerHTML=txt;
    </script>
  </body>
</html>

The thing is that I want to read a text file that continuously changes: http://arbsq.net/dchampolu/champolu_data.txt

when I run this function once, the browser caches the text file, and then every time I run the code, it only gets the cached version, not the updated version.

I can always tell the users to clean this cache and this sort of stuff, but is there a way by JavaScript or jQuery to force the browser to use only the current version of the file, not the cached version?

3
  • hey you have to add some dummy random number in the end of ajax url eg: arbsq.net/dchampolu/champolu_data.txt?123456 Commented Dec 21, 2014 at 15:52
  • looks like a smart solution, I'll try it, can you post it as an answer so that I accept it :) Commented Dec 21, 2014 at 16:03
  • it is good, please post it as an answer Commented Dec 21, 2014 at 16:04

2 Answers 2

5

You can set up the server to tell the client not to cache the file or you can use a cache buster in the url.
For cache busting just add a query string with a unique value at the end

rawFile.open("GET", file+'?dc='+(new Date()).getTime(), false);
Sign up to request clarification or add additional context in comments.

Comments

2

for dummy random number you can use timestamp too eg: 'http://arbsq.net/dchampolu/champolu_data.txt?' + (new Date()).getTime()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.