简体   繁体   中英

PHP statements inside javascript external file

I need to do javascript action depends on $_SESSION php status:

    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. How am I supposed to use PHP statements in this JS file? My code doesnt work :c

PHP runs on the server, Javacript run on the browser. You can pass information from PHP to Javascript, and you can pass information to the server FROM 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

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

Then your JavaScript can do whatever it needs to with that.

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 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>'; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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