0

当我输入:

<?php
  $temp="1234";
  echo "<script type='text/javascript'>document.write({$temp});</script>";
?>

我在屏幕上得到 1234。

但是当我替换$temp="1234"为时$temp="alfa",屏幕上什么也没有。

有什么问题 ?我哪里错了?“1234”和“alfa”都是字符串

4

2 回答 2

2

alert(1234) is valid javascript, and will simply pop up the integer 1234 on your screen. alert(alfa) is attempting to pop up the contents of a variable named alfa on your screen, which doesn't exist.

If you're insert data from PHP into a Javascript context, you MUST use json_encode() to ensure that you're producing VALID javascript. e.g.

$temp = 'alfa';
$json=  json_encode($temp);
echo '<script>.... {$json}...</script>';

that will produce alert('alfa') and work as expected.

于 2013-10-11T19:20:53.417 回答
0

您没有将文本括在表示字符串的双引号字符 '"' 中。

document.write(1234)之所以有效,是因为1234它是 JavaScript 中的有效值(整数),而alfa它是符号名称,它应该是"alfa".

于 2013-10-11T19:19:15.080 回答