开发者

[PHP/JavaScript]: Get PHP session value in other file's JavaScript function

I have a PHP file and it holds a value in t开发者_开发百科his session variable: $_SESSION['image_value'].

I want this session value in a JavaScript function. Actually, I want to match a string in my JavaScript function with this session value.

Anyway I can do this?


You could use json_encode():

<script type="text/javascript">
    var image_value = <?php echo json_encode($_SESSION['image_value'], JSON_HEX_TAG); ?>;
</script>

But be aware that PHP is entirely server-side and javascript is entirely client-side. That variable will be set when the page loads and any javascript modifications to it will not be preserved in the session.


In your javascript code, instantiate x like this:

var x = "<?=$_SESSION['image_value']?>";

then just use it to do your comparisons or whatever. Of course, the script has to be evaluated by the server first, so putting this inside a .js file will not work. You need to put this in the .php file, in a tag. Maybe to this then call a function in a js file if you need to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜