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

标签 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>
";

?>

最佳答案

它不起作用,因为 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>

希望对您有帮助!

关于javascript - 将 PHP 变量传递给 Javascript 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32083969/

相关文章:

javascript - 在 Angular 中设置 Angular Web 组件的样式

php - MySQL MATCH 关键字开头的通配符

android - isRecognitionAvailable 在 android 上返回 false

python - Python 中的 Microsoft Azure 语音转文本功能的字幕/说明文字

javascript - 不使用innerHTML获取innerHTML

javascript - GTM dataLayer .push 创建一个新对象,而不是将其添加到现有 dataLayer

javascript - fullpage.js:在容器内使用鼠标指针滚动时禁用页面滚动

php - 将类别从父可配置产品复制到 Magento 中的简单子(monad)产品

php - 从 MySQL 数据库中选择的数据不显示

android - android 的语音增强/降噪/降噪库