scritp里怎么传值给php,如何将PHP变量传递给javascript?

这篇博客探讨了如何将PHP的session_id()转换为JavaScript变量时遇到的问题。作者尝试了直接输出的方式但未成功,并提出了使用PHP的json_encode()函数来确保输出的JavaScript变量是有效的。文中强调了json_encode()的重要性,因为它能保证生成的JavaScript代码语法正确,同时也提醒注意转义问题。
摘要由CSDN通过智能技术生成

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; ?>";

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值