我想将 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。 JavasScript 中的变量 rightAnswer
应采用该值
php 变量 $ CorrectAnswer
。任何帮助将不胜感激。预先感谢您!
最佳答案
在 PHP 的 while 循环中执行此操作
$question=$row['description']."of ".$row['text']."?|".$row['answer'];
echo($question);
在你的java脚本中
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var elements = xmlhttp.responseText.split("|");
document.getElementById("question").innerHTML=elements[0];
var rightAnswer = elements[1];
alert(rightAnswer);
}
这是一个想法。将其更改为您想要的方式。
关于php - 将 php 变量传递到 JavaScript 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333194/