我想将一个 php 变量传递给 JavaScript。我必须从数据库中获取问题(随机地,一个一个地),如果最终用户回答正确,那么程序正在做其他事情。
数据库
+------+-----------------------+---------------+-----------------+
| q_id | description | text | answer |
+------+-----------------------+---------------+-----------------+
| 1 |What is the capital | United States | Washington D.C. |
| 2 |What is the capital | California | Sacramento |
| 3 |What is the capital | Maryland | Annapolis |
+------+-----------------------+---------------+-----------------+
在 php 文件中,变量$question
和$correctAnswer
具有以下值:
php代码:
$sql="SELECT description, text, answer FROM Questions";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$question=$row['description']."of ".$row['text']."?";
echo($question);
$correctAnswer=$row['answer'];
//echo($correctAnswer);
}
javascript代码:
var rightAnswer;
function takeQuestion()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("question").innerHTML=xmlhttp.responseText;
rightAnswer ='<?php echo $correctAnswer;?>';
alert(rightAnswer);
}
}
xmlhttp.open("GET","getQuestion.php",true);
xmlhttp.send();
}
该程序正在随机打印问题,但我在将变量传递
$correctAnswer
给 Javascript 时遇到问题。JavaScript 中的变量rightAnswer
应该取 php 变量的值$correctAnswer
。任何帮助将不胜感激。先感谢您!