代码之家  ›  专栏  ›  技术社区  ›  big boi

如何使php标记可以在js脚本和php代码中运行?复制

  •  0
  • big boi  · 技术社区  · 1 年前

    我正试图为一个在配置文件上显示名称的页面编写php脚本 所以我需要做的是用php连接到SQL,并用php获取用户id, 然后使用JS使用php变量写入元素的信息。

    <?php
    if ($result = $mysqli -> query($sql)) {
        if ($result -> num_rows == 1) {
            $row = $result->fetch_assoc();
            $un = $row['username'];
            echo '<script type="text/javascript">
                var myvar = '<?php json_encode($un, JSON_UNESCAPED_UNICODE)?>'; // this line
                const user = document.getElementById("ctl00_cphUserPane_lUserURL");
                const name = document.getElementById("ctl00_cphUserPane_lUserName");
                name.textContent = myvar;
                user.textContent = myvar + ".s Page";
            </script>';
        }
    }
    ?>
    

    我试过更改我使用的引号类型,但没有成功 我在堆栈溢出上搜索了如何在js脚本中包含php标记,但当我使用那里的代码时,这也不起作用

    脚本中的代码运行,但我不知道如何运行php代码,因为它在js脚本中。 我使用console.log来确保脚本真正运行在echo中

    1 回复  |  直到 1 年前
        1
  •  0
  •   Barmar    1 年前

    您不需要从JavaScript运行PHP。只需将PHP变量连接到要回显的字符串即可。

    <?php
    if ($result = $mysqli -> query($sql)) {
        if ($result -> num_rows == 1) {
            $row = $result->fetch_assoc();
            $un = json_encode($row['username'], JSON_UNESCAPE_UNICODE);
            echo '<script type="text/javascript">
                var myvar = ' . $un . ';
                const user = document.getElementById("ctl00_cphUserPane_lUserURL");
                const name = document.getElementById("ctl00_cphUserPane_lUserName");
                name.textContent = myvar;
                user.textContent = myvar + ".s Page";
            </script>';
        }
    }
    ?>