calling php function in javascript refresh

前端 未结 2 577
慢半拍i
慢半拍i 2021-01-26 09:34

I have this simple function in javascript to refresh a page after a set time.

function AutoRefresh( t ) {
    setTimeout(\"location.reload(true);\", t);
}


        
相关标签:
2条回答
  • 2021-01-26 10:32

    I'm afraid the answer is no. By the time JavaScript has been run on your page, the server side (PHP) has already finished processing. Your best bet is to accomplish what you need before the page load, or accomplish it with JavaScript alone.

    0 讨论(0)
  • 2021-01-26 10:38

    If you are refreshing the page, you're effectively reloading it from the server, so any 'onload' events will fire again. The page will render again from scratch. You can call a PHP script using AJAX in some 'onload' Javascript listener if you like, though. e.g. with JQuery:

     <html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
        <script type="text/javascript">
    
        $(document).ready( function () {
    
            setTimeout("location.reload(true);", 2000);
    
            $.get('home.html', function(ret){
                $('body').html(ret);
            });
    
        });
    
        </script>
        </head>
        <body>
            <h1>Test</h1>
    
        </body>
        </html>
    

    Beware of calling setTimeout() recursively though as it can make a page unresponsive over time. You may find this useful:

    http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

    0 讨论(0)
提交回复
热议问题