简体   繁体   English

在JavaScript刷新中调用php函数

[英]calling php function in javascript refresh

I have this simple function in javascript to refresh a page after a set time. 我在javascript中有这个简单的功能,可以在设定的时间后刷新页面。

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

Now after every refresh, I want it to call a PHP function, for example: 现在,每次刷新后,我都希望它调用PHP函数,例如:

function writeName()
{
echo "Refresh me";
}

Is it possible to call the PHP function in JavaScript after every refresh? 每次刷新后是否可以在JavaScript中调用PHP函数? Thanks 谢谢

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. 在页面上运行JavaScript时,服务器端(PHP)已完成处理。 Your best bet is to accomplish what you need before the page load, or accomplish it with JavaScript alone. 最好的选择是在页面加载之前完成所需的工作,或者仅使用JavaScript来完成。

If you are refreshing the page, you're effectively reloading it from the server, so any 'onload' events will fire again. 如果要刷新页面,则可以从服务器有效地重新加载页面,因此任何“ onload”事件都会再次触发。 The page will render again from scratch. 该页面将再次从头开始呈现。 You can call a PHP script using AJAX in some 'onload' Javascript listener if you like, though. 不过,您可以根据需要在一些“ onload” JavaScript侦听器中使用AJAX调用PHP脚本。 eg with JQuery: 例如与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. 尽管要递归调用setTimeout(),但要小心,因为它会使页面随着时间的推移而无响应。 You may find this useful: 您可能会发现这很有用:

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

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

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