doushan3511 2013-12-13 12:38
浏览 46
已采纳

PHP在文件顶部加载javascript函数

This topic is the follow-up of this one PHP + Session doesn't login at first time.

I've solved my issue of Cookies/Sessions by changing the code to the top of everything, before <html>, previously I was writing my php code after the </html> tag.

With this change I've lost the output of javascript plugin (http://fabien-d.github.io/alertify.js/).

Simple example:

if(Cookie::Exists('page-main-login-cookie')){
    echo "<script type='text/javascript'>page_add_success('OK')</script>";
}

This no longer works, I do understand why, because the javascript files are AFTER the <html>, and I'm calling the function before.

<script src="js/alertify/js/alertify.min.js"></script>
<script type="text/javascript">
    function page_add_success(msg){
        alertify.success(msg);
    }
</script>

I've found some topics on stackoverflow about including the right scripts before calling the function in php. Something like:

<?php 
    echo "<script src='js/jquery-1.9.1.min.js'></script>";
    echo "<script src='js/jquery.mobile-1.3.2.min.js'></script>";
    echo "<script src='js/alertify/js/alertify.min.js'></script>";
?>

So, in the end, the top of my file would be:

include('headscript.php');

if(Cookie::Exists('page-main-login-cookie')){
    echo "<script type='text/javascript'>page_add_success('OK')</script>";
}
<html>
    <head>
    <script type="text/javascript">
        function page_add_success(msg){
            alertify.success(msg);
        }
    </script>
    </head>
</html>

But the function continues to be on below of the PHP..and doesn't work. Any ideas? Thanks.

  • 写回答

4条回答 默认 最新

  • douhulao7642 2013-12-13 12:51
    关注

    I guess this helps,

    instead of echoing it in php, pass it to a variable and use after the header.

    eg:

      <?php 
       if(Cookie::Exists('page-main-login-cookie')){
        $page= "<script type='text/javascript'>page_add_success('OK')</script>";
            }
      ?>
    

    and then echo it after the header using,

       <?php echo $page; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。