简体   繁体   中英

Javascript include file and refresh every 30 seconds

I have 3 files i refer to them as:

     $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

'.$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. I'm thinking javascript jquery may be the one but i'm not too familiar with it.

Many thanks!

If you have jQuery

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

with javascript kinda like

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. Just use the setInterval() method in JavaScript to have it repeatedly run a function on a schedule. Since you're rather new to this I'll try to make a simple example. The code below runs updateDiv() every 30 seconds.

<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/

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