简体   繁体   中英

How to print a .txt file content in a html site with javascript every 1 s?

I have a file in my directory which is constantly changing itself. So every 1 second my file is saved and has a diffenent content. How can I display the file content in a HTML site using javascript in a way that the file content is updated in real time or every 1 s?

I tried this code but the site just opens the pop-up window where the file content is and every time I want to see changes, I have to press F5, I don't want that.

<html>
<head>

</head>
<title>test</title>
<body>
<a href="output.txt">test</a><br>

    <script>
        var w = window.open('output.txt'); //Required full file path.
        w.print();
    </script>
</body>
</html>

I would go along the lines of

</head>
<title>test</title>
<body>
<a href="output.txt">test</a><br>
    <div id="text" ></div>
    <script>
        setInterval(()=>{
               let t=new XMLHttpRequest()
               t.open('GET',location.origin+'output.txt')
               t.onreadystatechange=(ev)=>{
                   if(ev.readyState==4){    
                       document.getELementById('text').textContent=t.responseText;
                      }
                };
                t.send()
         },1000);
    </script>
</body>
</html>

this way you wont get a new popup every second another way would be :

<html>
<head>

</head>
<title>test</title>
<body>
<br>
    <iframe id="text" src="output.txt" />
    <script>

        setInterval(()=>{ 
            document.getElementById("text").contentWindow.location.reload();
         },1000);
    </script>
</body>
</html>

Use the following code:

 <html> <head> </head> <title>test</title> <body> <a href="output.txt">test</a><br> <script> var w = window.open('output.txt'); //Required full file path. w.print(); setInterval(function() { window.location.reload(true); }, 1000) </script> </body> </html> 

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