如何刷新/重新加载php函数而无需刷新整个页面?

时间:2019-08-16 02:06:55

标签: javascript php ajax

我有一个php文件,在其中我调用了不同的php函数来呈现页面。我想通过再次调用php函数每5分钟刷新页面的一部分。我的网站可以正常工作,但是如果不重新加载整个页面就无法更新内容。

php文件1 index.php

<?php
    //  Enable functionality
    require_once ("lib/config.php"); //this file has all my php includes and db configurations

    site_head();

    front_stats();

    front_browser(20);

    site_foot();
?>

php文件2,其中包含上述功能-layout.php

<?php
    function front_stats ()
    {
        //my content thats rendered on the page
    }

    function front_browser ($per_page)
    {
        //my content thats rendered on the page
    }

    etc.
?>```

1 个答案:

答案 0 :(得分:2)

将要重新加载的部分设置为特殊标签,即

<div id=reload></div>

然后设置一个新的.php文件,该文件将仅返回应替换为重新加载部分的html代码。

现在包括一个Javascript文件,该文件通过ajax请求定期访问此php文件。
除了ajax请求本身之外,您还需要获取新内容并覆盖旧内容。这是ajax和替换部分的示例:

xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=function({
    if(this.readyState==4&&this.status==200{
        document.getElementById("reload").innerHTML=this.responseText
    }
};
xmlhttp.open("GET","yournewphppagename.php",true);
xmlhttp.send();