【问题标题】:Loading PHPs via XMLHTTPRequest don't share the same variable scope通过 XMLHTTPRequest 加载 PHP 不共享相同的变量范围
【发布时间】:2018-06-08 14:46:53
【问题描述】:

我了解 PHP 中全局变量的概念,并了解使用全局变量的优缺点。尽管如此,我还是决定使用它们,但我遇到了关于它们的范围和可见性的问题。

情况:

根据菜单的选择,我将不同的 PHP 加载到一个 div 中。 PHP 需要相同的公共数据集,我希望避免为每个 PHP 重新加载并一直保存在内存中。在下面的示例中,GlobalVars.php 将在内存中保存两次,并且还会从数据库中获取数据两次。

问题是,通过将它们加载到 div 中,它们不共享 main.html 的范围。 GlobalVars.php 中的全局变量可以通过another.php 中的代码看到和访问,但在PHP1.php 中和PHP2.php 中都看不到。

GlobalVars.php:

<?php
    $var1 = "*";
    $var2 = 5;
    // Various SQL fetches
?>

Main.html:

<?php require_once="./GlobalVars.php"; ?>
<?php require_once="./another.php"; ?>

<script>
    function LoadHTML(href) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", href, false);
        xmlhttp.send();
        return xmlhttp.responseText;   
    }

    switch(menuitem) {
        case 0: break;
        case 1: document.getElementById("contentdiv").innerHTML=LoadHTML("./PHP1.php") break;
        case 2: document.getElementById("contentdiv").innerHTML=LoadHTML("./PHP2.php") break; break;
        case 3: break;
        default:
    }
</script>

PHP1.html:

<?php
    require_once="./GlobalVars.php";
    // code ...
?>

PHP2.html:

<?php
    require_once="./GlobalVars.php";
    // code ...
?>

问题是,如何将 PHP 加载到 div 中并“查看”并使用 main.html 范围内的变量?

问候

卡斯滕

【问题讨论】:

  • 它不起作用,因为javascript是在客户端执行的。而php是一种服务器端语言。你也可以在需要 php1 和 php2 之前只需要 globalvars,这样你就不必在这些文件中再次需要 globalvars。
  • @Sjoerd de Wit:实际上,我确实需要 GlobalVars.php 就在 main.html 的开头。但是当它到达 javascripts 时,PHP 引擎已经完成并且内存正在被 GC 释放。用 JS 启动另一个 PHP,然后它将分配自己的变量范围(堆),而不是重新使用之前运行的 PHP 中的那个。我下面描述的解决方案现在对我有用。

标签: php html scope xmlhttprequest global-variables


【解决方案1】:

我通过不通过JS加载PHP1和PHP2解决了这个问题,而是在PHP引擎运行的早期。我现在没有将 PHP 加载到相同的 DIV 中,而是将它们加载到不同的 DIVs 中。这些DIVs 的可见性随后将通过 JS 进行控制。

变量 $LastScreen 正在从 SQL 数据库中提取,并包含显示的最后一个屏幕,以便用户获得与重新加载页面之前相同的屏幕。

DIVs 的生成:

<html>
    <body>
        <div class="myclass" id="screen1"
            <?php if (strcmp($LastScreen, "screen1") !== 0) {echo " style=\"display:none; \"";} ?>
        >
            <?php require_once './PHP1.php'; ?>
        </div>
        <div class="myclass" id="screen2"
            <?php if (strcmp($LastScreen, "screen2") !== 0) {echo " style=\"display:none; \"";} ?>
            >
            <?php require_once './PHP2.php'; ?>
        </div>
    </body>
</html>

在 JS 中切换屏幕:

<script>
    function SwitchScreen (screen){
        var arr = document.getElementsByClassName('myclass');
        var i;
        for (i=0; i < arr.length;i++) {
            arr[i].style.display = "none";
            }
        document.getElementById(screen).style.display = "inline";

        // push screen name to SQL
        // ...
    }
</script>

问候

卡斯滕

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2011-11-11
    • 2014-04-27
    • 2018-07-30
    • 2017-04-17
    • 2017-01-17
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多