dtnrsmi824877 2013-02-13 09:09
浏览 71

在Javascript代码中使用PHP代码

Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.

This is the way I currently write the code:

<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>

Any ideas how to avoid using PHP inside Javascript in this particular example?

  • 写回答

5条回答 默认 最新

  • dongshan1811 2013-02-13 09:14
    关注

    If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)

    For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.

    In my opinion you should decide if its worth the effort.

    Edit:

    In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:

    <?php
    if(!empty($_SESSION['authorized'])) :
    ?>
    <script type="text/javascript">
    function execute_this() {
    some code;
    }
    
    execute_this();
    </script>
    <?php
    endif;
    ?>
    

    If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.

    评论

报告相同问题?

悬赏问题

  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改