我正在尝试编写一个游戏,您可以掷骰子并获得一半的报价,并且您必须猜测它是否与最初给出的一半相匹配。我正在使用 AJAX,一切都工作正常,直到最后我使用
将变量从 php 发送到 javascriptecho '<script>currentQuote = $currentQuote;</script>';
它显示在页面上,但是当我检查 JS 中 currentQuote 的值时,它是未定义的。这是游戏简化版本的链接,仅显示我的问题。 http://workwithu.com/Games/Game15snip.php您看不到的 PHP 代码是:
<?php
$response = mt_rand(1,6);
echo $response;
$currentQuote=$response;
echo '<script>currentQuote = $currentQuote;</script>';//this not working
echo "<br>";
echo "currentQuote is:";
echo $currentQuote; //this shows on the screen fine
?>
任何帮助将不胜感激。我已经没有办法尝试了。 谢谢
最佳答案
基本 PHP 语法。 '
引用的字符串不插入变量值。如果您在页面上执行查看源代码
,您将看到一个文字
<script>current Quote = $currentQuote</script>
在页面的源代码中。切换到 "
带引号的字符串:
echo "<script>currentQuote = $currentQuote;</script>";//this not working
^---note ^---note
关于javascript - 使用 PHP 设置 Javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575126/