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_var = session_id();
?>
js_var = <?php echo($php_var ?>;
This seems like it should work for me but it doesnt can anyone suggest a better way?
解决方案
The best method i can think of looks like this:
$php_var = session_id();
?>
var js_var = <?php echo json_encode($php_var); ?>;
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_var = session_id();
?>
var js_var = "<?php echo $php_var; ?>";