每 15 秒读取一次文本文件的内容 [英] Read the contents of a text file every 15 seconds

查看:30
本文介绍了每 15 秒读取一次文本文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个音乐网站上工作:我在服务器上有一个文本文件,其中包含当前正在播放的歌曲的名称.我想每十五秒读取一次文本文件,并更改我网站上显示的文本,没有刷新.

I'm working on a music site: I have a text file on the server which contains the name of the currently playing song. I would like read the text file every fifteeen seconds, and change the text displayed on my site, without a refresh.

现在,使用一点 jQuery 和 javascript,我实际上已经到了第一次读取和显示文件的程度,但它不会刷新.我已经尝试了各种 setInterval 函数,但在我的一生中,我无法让这部分工作.任何帮助将不胜感激.

Now, using a little jQuery and javascript, I have actually gotten to the point where the file is read and displayed the first time, but it wont refresh . I have attempted all sorts of setInterval functions, but for the life of me I cant get this part to work. Any help would be greatly appreciated.

这是我所拥有的:

<script type="text/javascript"> 
$(document).ready(function() {
    jQuery.get('http://www.XXXXX.com/nowplaying/NowPlaying.txt', function(data) {
        var myvar = data;
        var parts = myvar.split(/\n/);
        var songtitle = parts[0];
        var songartist = parts[1];
        var songalbum = parts[2];
        var songtime = parts[3];
        $('#songtitleholder').html(songtitle);
        $('#songartistholder').html(songartist);
        $('#songalbumholder').html(songalbum);
    });
});​
</script>

推荐答案

你可以把你想repeatedly 执行的代码放在函数里,然后把那个函数传入setTimeout.setTimeout 的第二个参数以 millisecond 为单位.

You can put the code you want to execute repeatedly in function and pass that function in setTimeout. The second parameter of setTimeout will take interval in millisecond.

在此处使用 setTimeout IMO 在这里更合适,因为它将排除发送请求和接收响应所花费的时间.它会收到响应后每5秒发送一次请求.

Using setTimeout here IMO is more appropriate here as It will exclude the time taken for send request and receiving response. It will send request every 5 second after receiving response.

<script type="text/javascript"> 

 $(document).ready(function() {

    function functionToLoadFile(){
      jQuery.get('http://www.XXXXX.com/nowplaying/NowPlaying.txt', function(data) {
       var myvar = data;
       var parts = myvar.split(/\n/);
       var songtitle = parts[0];
       var songartist = parts[1];
       var songalbum = parts[2];
       var songtime = parts[3];

       $('#songtitleholder').html(songtitle);
       $('#songartistholder').html(songartist);
       $('#songalbumholder').html(songalbum);
       setTimeout(functionToLoadFile, 5000);
    });
    }

    setTimeout(functionToLoadFile, 10);
});

</script>

这篇关于每 15 秒读取一次文本文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆