Updating html code with javascript when php return

2019-07-16 05:14发布

I want to continuously update an html document using the return of a php file. Therefore I need to use the jQuery function:

$.get('returnfunction.php', function(data) { 
test=data;
document.getElementById('t1').innerHTML=test; 
}); 

How can I call this function continuously in javascript? setInterval seems not proper for this asynchronous function.

Thanks

2条回答
SAY GOODBYE
2楼-- · 2019-07-16 05:49

setInterval probably isn't a good idea since the order is not guaranteed, therefore you could be sending requests every X amount of seconds that either come back all at once, not at all, or in a random order. You can use setTimeout in the callback to start another request in X amount of time:

function getStuff() {
    $.get('returnfunction.php', function(data) { 
        test=data;
        document.getElementById('t1').innerHTML=test; 
        setTimeout(getStuff, 5000); //Run this func again in 5 sec
    }); 
}
查看更多
仙女界的扛把子
3楼-- · 2019-07-16 05:57

The problem with calling an asynchronous function using setInterval is that the unanswered requests might accumulate if the server or the network is slow.

Here's how you might do it :

(function doOne(){
    $.get('returnfunction.php', function(data) { 
       test=data; 
       document.getElementById('t1').innerHTML=test;
       setTimeout(doOne, 1000);
    }); 
})();

This way the next call to $.get occurs one second after the server has answered the last call.

You might also want to act on failures, not just on success, depending on your exact requirements.

查看更多
登录 后发表回答