使用 PHP 设置一个 Javascript 变量


set a Javascript variable with PHP

我正在尝试编写一个游戏,让您掷骰子并获得半个报价,您必须猜测它是否与您最初给出的一半匹配。我正在使用 AJAX,直到最后我将变量从 php 发送到 javascript 时

,一切都很好
echo  '<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语法。 ' 带引号的字符串不会插值变量值。如果您在页面上执行view source,则会看到一个文字

<script>current Quote = $currentQuote</script>

在页面的源中。切换到带引号"引号的字符串:

echo "<script>currentQuote = $currentQuote;</script>";//this not working
     ^---note                                       ^---note

如果你使用' -引号刺,你应该使用。

echo '<script>currentQuote = '.$currentQuote.';</script>';

或使用" -引用

echo "<script>currentQuote = $currentQuote;</script>";