douruduan8812 2017-03-03 02:48
浏览 22

如何在PHP文件中使用PHP里面的PHP

I have a php file in which i have added JS inside echo. I want to use php function inside that JS scope now, how can i do that:

<?php
  echo '<script>
    <?php 
      function message() {
        echo "You will be redirected";
      } 
    ?>
    setTimeout(<?php message();>?,3000);</script>';
?>
  • 写回答

2条回答 默认 最新

  • doushi3202 2017-03-03 02:54
    关注

    PHP will execute first, on the server, so you would have to code it in a .php file, to ensure the server runs it through PHP, then have it embed the PHP in the JavaScript like so:

    <script>
    function message(){
        alert("<?= $phpMessage ?>");
        location.href = "http://www.example.com" /* The URL you would like the user to go to next */;
    }
    setTimeout(message,3000);
    </script>
    

    Assuming you want to display a message from PHP, you may embed it in an alert statement as <?= $phpMessage ?>. This will be awkward for your users.

    A more graceful solution would be to use session storage to pass a message to the next page.

    On the page that is receiving the data and needs to send a message, the first PHP command, before any output is sent should be session_start(). A message may be saved in a session variable with $_SESSION['message'] and it will be available for the next script, like so:

    one.php (first page)

    <?php session_start(); $_SESSION['message'] = 'My Message'; 
    

    two.php (second page)

    <?php session_start(); echo $_SESSION['message']; unset($_SESSION['message']); ?>
    

    Notice that the second script must use unset to clear the message.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件