如何将Php变量值分配给Javascript变量?(复制)

时间:2022-08-27 17:51:13

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?

价值不警惕。这个错误是什么?

5 个解决方案

#1


51  

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>

#2


6  

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

#3


4  

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变量(并转义换行)

#4


2  

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

在 确保Javascript接受它为字符串,同时考虑转义。

#5


0  

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

#1


51  

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>

#2


6  

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

#3


4  

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变量(并转义换行)

#4


2  

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

在 确保Javascript接受它为字符串,同时考虑转义。

#5


0  

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