最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I pass a PHP variable to javascript? - Stack Overflow

programmeradmin0浏览0评论

I want to use a PHP variable as a javascript variable - specifically I want to user the PHP variable session_id(); and use this as a javascript variable.

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = <?php echo($php_var ?>;
</script>

This seems like it should work for me but it doesnt can anyone suggest a better way?

I want to use a PHP variable as a javascript variable - specifically I want to user the PHP variable session_id(); and use this as a javascript variable.

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = <?php echo($php_var ?>;
</script>

This seems like it should work for me but it doesnt can anyone suggest a better way?

Share Improve this question asked Sep 7, 2010 at 11:00 undefinedundefined 5,32812 gold badges59 silver badges91 bronze badges 1
  • 1 duplicate. please use the search function. – Gordon Commented Sep 7, 2010 at 11:03
Add a comment  | 

4 Answers 4

Reset to default 13

The best method i can think of looks like this:

<?php
$php_var = session_id();
?>
<script type="text/javascript">
    var js_var = <?php echo json_encode($php_var); ?>;
</script>

PHP's json_encode-function is always producing valid JavaScript, which is not ensured if you are simply outputting random values. If you decide not to use json_encode(), you should at least enclose the php-value with quotes to prevent syntax errors. Be aware of escaping!

<?php
$php_var = session_id();
?>
<script type="text/javascript">
   var js_var = "<?php echo $php_var; ?>";
</script>

That's just fine. Be sure that if the variable you're echoing is a string that you put quotes around it and escape any quotes, newlines, etc. inside it -- e.g., make sure it really gets output as a valid JavaScript string literal. Also, don't forget the var before js_var.

It seems you have opened a parenthesis in the echo call, but didn't close it. Also, you should place a semicolon after it. You've also forgotten the quotes (as Gordon says in the comment below).

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = "<?php echo($php_var); ?>";
</script>

P.S.You can use less code by replacing echo with the '=' character:

js_var="<?=$php_var?>";

It doesn't work because your snippet contains errors, it should be:

<?php
$php_var = session_id();
?>
<script language="JavaScript" type="text/javascript">
js_var = <?php echo $php_var ?>;
</script>
发布评论

评论列表(0)

  1. 暂无评论