简体   繁体   中英

how to get php session value in javascript file

i have a php file in which i am calling external takeatour.js file in that js file i want php session data.by using a code....

$(this).ready(function() {

    var category = <?php echo json_encode($this->session->userdata('category')); ?>;     
   alert("category="+category);
});

is it correct?? plz give me some suggestion. Thanks!!

You can pass the session variable from PHP code to javascript code like this:

 <?php $variablephp = $_SESSION['category']; ?> <script> var variablejs = "<?php echo $variablephp; ?>" ; alert("category = " + variablejs); </script> 

Add .php to the end of the javascript file. That way the server will process it.

If you include it in a page that a client will download later, make sure to type=text/javascript" in your script tag because it won't be happy with the extension otherwise.

Whatever editor you use will likely not syntax highlight properly since you will not be following php conventions.

you can pass the category value as a parameter in the src attribute. For example:

<script src="myjs.js?category=<?php echo $this->session->userdata('category'); ?>"></script>

and then get the category value inside your 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