将PHP变量传递给Javascript无法正常工作

时间:2015-08-18 23:01:19

标签: javascript php speech-recognition text-to-speech

我正在尝试将php变量传递给javascript,但它似乎不起作用。我知道它只适用于javascript,只是当我试图用PHP传递它时它不起作用。我做错了什么?

<?php

$sayIt = "Hello";

echo "
<script type = 'text/javascript'>

var msg = new SpeechSynthesisUtterance($sayIt);
window.speechSynthesis.speak(msg);

</script>
";

?>

1 个答案:

答案 0 :(得分:3)

它不起作用,因为PHP将解释这样的代码:

<script type = 'text/javascript'>

var msg = new SpeechSynthesisUtterance(Hello);
window.speechSynthesis.speak(msg);

</script>

然后JavaScript会将Hello视为一个变量,可能没有在JavaScript中定义,你可能会这样写:

echo "<script type = 'text/javascript'>

var msg = new SpeechSynthesisUtterance(\"$sayIt\");

window.speechSynthesis.speak(msg);

";

然后它将被解释为:

<script type = 'text/javascript'>

var msg = new SpeechSynthesisUtterance("Hello");
window.speechSynthesis.speak(msg);

</script>

希望它会对你有所帮助!