简体   繁体   English

使用Javascript动态读取和显示txt文件

[英]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. 我试图读取一个txt文件并在我的网页中显示其内容,因为它的内容会随着时间的推移而变化,我想定期更新它。 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 如果您希望每隔3秒刷新一次,请使用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}) . 您的ajax结果可能会被缓存尝试设置$.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? 另外我不确定你想用setTimeout实现什么,你是否试图在3 + 1秒后加载页面?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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