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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?