dovhpmnm31216 2016-07-07 19:28
浏览 82
已采纳

无法在<script>标签内回显PHP变量? [关闭]

This is my PHP code. I want error to be displayed using an alert window.

 if ($projectid=="")
  {
    $error = 'You must choose a project.
              Click &lsquo;back&rsquo; and try again.';
    include error.html.php';
    exit();
  }

This is error.html.php that is supposed to be parsed by the browser

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Script Error</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">


    </head>

    <body>

         <script> 
             var error = <?php echo   $error ; ?>;
              window.onload = function(){ alert(error); }
         </script>
    </body>
</html>

Wahts up with the script tags ? Do they prevent PHP from running ?

  • 写回答

5条回答 默认 最新

  • douyu9012 2016-07-07 20:20
    关注

    The real problem is that this is what your rendered result looks like:

    var error = You must choose a project.
                Click &lsquo;back&rsquo; and try again.
    

    Does that looks like valid JavaScript to you? I think not.

    var error = <?=json_encode($error);?>;
    

    That should result in:

    var error = "You must choose a project.
                     Click &lsquo;back&rsquo; and try again.";
    

    Much better.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数