简体   繁体   中英

Using Javascript to read and display a txt file dynamically

I was trying to read a txt file and display its content in my web page, since its content changes over time, I want to update it periodically. Here is my code, it displays the content at first, but it won't change after I changed the file's content. Any suggestions? Thanks.

<script type="text/javascript">
        setTimeout(read(),3000);
    function read(){
    setTimeout(jQuery.get('now.txt',function(data){
    document.write(data);}),1000);
    }
</script>

Nearly there. Change:

setTimeout('read', 3000);
           ^^^^^ here

and here:

function read(){
    jQuery.get('now.txt',function(data){document.write(data);});
}

If you want it to refresh every 3 seconds use setInterval

Documentation:

the function name does not need to be closed. It also does not need to be a string.

change this

setTimeout(read(),3000);

to this

setTimeout(read, 3000);

Your ajax results might be cached try setting $.ajaxSetup({cache: false}) . Also I'm not sure what you are trying to achieve with the setTimeout s, are you trying to load the page after 3+1 seconds?

<script type="text/javascript">
    $.ajaxSetup({cache: false})
    setTimeout(read, 3000);
    function read(){
        jQuery.get('now.txt',function(data){
        document.write(data);});
    }
</script>

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