如何将 Php 变量值分配给 Javascript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5895842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:24:53  来源:igfitidea点击:

How to assign Php variable value to Javascript variable?

phpjavascripthtml

提问by Ravichandran Jothi

Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?

可能的重复:
将 PHP 变量传递给 Javascript 的最佳方法是什么?

I am using the following code:

我正在使用以下代码:

<script type="text/javascript">
<?php $ctnme = $_SERVER['REQUEST_URI'];
$cnme = explode("/",$ctnme);
echo $cname = $cnme[1];
?>
var spge = <?php echo $cname; ?> ;
alert(spge);
</script>

The value doesn't alert. What is the mistake?

该值不会发出警报。什么是错误?

回答by Cups

Essentially:

本质上:

<?php
//somewhere set a value
$var = "a value";
?>

<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';

// then
alert(spge);

</script>

回答by Stefan Gehrig

The most secure way (in terms of special character and data type handling) is using json_encode():

最安全的方法(就特殊字符和数据类型处理而言)是使用json_encode()

var spge = <?php echo json_encode($cname); ?>;

回答by Frosty Z

Use json_encode()if possible (PHP 5.2+).

如果可能,请使用json_encode()(PHP 5.2+)。

See this one (maybe duplicate?): Pass a PHP string to a JavaScript variable (and escape newlines)

看到这个(可能是重复的?):将 PHP 字符串传递给 JavaScript 变量(并转义换行符)

回答by Dunhamzzz

Put quotes around the <?php echo $cname; ?>to make sure Javascript accepts it as a string, also consider escaping.

在 周围加上引号<?php echo $cname; ?>以确保 Javascript 接受它作为字符串,也考虑转义。

回答by Sai Sherlekar

**var spge = '';** 
alert(spge);