简体   繁体   English

javascript外部文件中的PHP语句

[英]PHP statements inside javascript external file

I need to do javascript action depends on $_SESSION php status: 我需要执行JavaScript操作取决于$ _SESSION php状态:

    if(isset($_SESSION['logged']) && $_SESSION['logged'] == true)
            {

echo <<<END

               $("#I-like-it").click(function()
               {

                 $(this).css({"font-size": "20px" });


               });
               $("#I-dont-like-it").click(function()
               {

                  $(this).css({"font-size": "20px" });


               });
END;

            }
            else
            {

               echo 'alert("You must be logged in to vote!")';


            }

This is external js file. 这是外部js文件。 How am I supposed to use PHP statements in this JS file? 我应该如何在此JS文件中使用PHP语句? My code doesnt work :c 我的代码不起作用:c

PHP runs on the server, Javacript run on the browser. PHP在服务器上运行,Javacript在浏览器上运行。 You can pass information from PHP to Javascript, and you can pass information to the server FROM JavaScript. 您可以将信息从PHP传递到Javascript,也可以将信息从JavaScript传递到服务器。 But they cannot execute at the same time. 但是它们不能同时执行。

What I suggest doing is to use Javascript to read your PHP variable while it loads 我建议做的是在加载时使用Javascript读取PHP变量

<script>
 var serverSession = <? echo $_SESSION['logged'] ?>
</script>

Then your JavaScript can do whatever it needs to with that. 然后,您的JavaScript可以执行此操作。

No, It can't, this is different type file, PHP is server side and JS is client side, but you can write javascript at your php file like this one : 不,不能,这是不同类型的文件,PHP是服务器端,JS是客户端,但是您可以像这样在您的php文件中编写JavaScript:

 <?php if(isset($_SESSION['logged']) && $_SESSION['logged'] == true) { echo ' <script> $("#I-like-it").click(function(){ $(this).css({"font-size": "20px" }); }); $("#I-dont-like-it").click(function(){ $(this).css({"font-size": "20px" }); }); </script> '; } else { echo '<script>alert("You must be logged in to vote!")</script>'; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM