简体   繁体   English

将PHP变量传递给Javascript不起作用

[英]Passing PHP variable to Javascript not working

I'm trying to pass a php variable to javascript, but it doesn't seem to be working. 我正在尝试将php变量传递给javascript,但似乎无法正常工作。 I know that it works with just the javascript, just that it doesn't work when I'm trying to pass it with PHP. 我知道它仅适用于javascript,只是当我尝试通过PHP传递时不起作用。 What am I doing wrong? 我究竟做错了什么?

<?php

$sayIt = "Hello";

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

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

</script>
";

?>

It doesn't work because the PHP will interpret the code like this: 这是行不通的,因为PHP会这样解释代码:

<script type = 'text/javascript'>

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

</script>

Then JavaScript will consider the Hello as a variable, which may not defined in JavaScript, you may should write it like this: 然后,JavaScript会将Hello视为一个变量,该变量可能未在JavaScript中定义,您应该这样写:

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

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

window.speechSynthesis.speak(msg);

";

Then it will be interpreted to this: 然后将其解释为:

<script type = 'text/javascript'>

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

</script>

Hope it will help you! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM