简体   繁体   中英

How can I load a PHP file every 5 seconds with JavaScript

I want a php program to be executed every 5 seconds using JavaScript. How can I do that?

I tried using:

<script type="text/javascript">
    setInterval(
        function (){
            $.load('update.php');
        },
        5000
    );
</script>

But it doesn't work.

Using jQuery and setInterval :

setInterval(function() {
    $.get('your/file.php', function(data) {
      //do something with the data
      alert('Load was performed.');
    });
}, 5000);

Or without jQuery:

setInterval(function() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
         if (request.readyState == 4 && request.status == 200) {
            console.log(request.responseText);
         }
      }
    request.open('GET', 'http://www.blahblah.com/yourfile.php', true);
    request.send();

}, 5000);

Try using setInterval() to perform a XHR call. ( jQuery , non jQuery )

setInterval(function() {
    // Ajax call...
}, 5000);

This will execute your code inside the function every 5 secs

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