简体   繁体   English

Javascript 包含文件并每 30 秒刷新一次

[英]Javascript include file and refresh every 30 seconds

I have 3 files i refer to them as:我有 3 个文件,我将它们称为:

     $nowplaying = file_get_contents("/api/static/nowplaying");
$dj = file_get_contents("/api/static/dj");
$listeners = file_get_contents("/api/static/listeners");

I want to call them in my php file inside div tags by using我想通过使用在 div 标签内的 php 文件中调用它们

'.$dj.'
'.$nowplaying.'
'.$listeners.'

but the contents of the files i am pulling update every 30 seconds so I need to refresh the data shown without refreshing the page.但是我每 30 秒更新一次文件的内容,所以我需要刷新显示的数据而不刷新页面。 I'm thinking javascript jquery may be the one but i'm not too familiar with it.我在想 javascript jquery 可能是其中之一,但我对它不太熟悉。

Many thanks!非常感谢!

If you have jQuery如果你有 jQuery

setInterval(function(){
    $.get("/api/static/nowplaying",function(data){
        // Do something with data
    });
},30000);

with javascript kinda like使用 javascript 有点像

var request = new XMLHttpRequest();
setInterval(function(){
    request.open('GET', '/api/static/nowplaying', true);
    request.send();
},30000)

request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = request.responseText;
    } else {
    // We reached our target server, but it returned an error

   }
};

Yes, I think using jquery/JavaScript is what you are looking for and its pretty simple.是的,我认为使用 jquery/JavaScript 是您正在寻找的,而且非常简单。 Just use the setInterval() method in JavaScript to have it repeatedly run a function on a schedule.只需使用 JavaScript 中的setInterval()方法让它按计划重复运行一个函数。 Since you're rather new to this I'll try to make a simple example.由于您对此很陌生,因此我将尝试举一个简单的示例。 The code below runs updateDiv() every 30 seconds.下面的代码每 30 秒运行一次updateDiv()

<script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js">
</script>
  <script type='text/javascript'>

var myVar
function updateDiv(){
    clearInterval(myVar);

    alert('your code should go here');

    myVar = setInterval("updateDiv()", 30000);
}
$(document).ready(function(){
    myVar = setInterval("updateDiv()", 30000);
}); 

You can view this here: https://jsfiddle.net/jglazer63/h6q20dj9/1/你可以在这里查看: https : //jsfiddle.net/jglazer63/h6q20dj9/1/

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

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