php - 将 php 变量传递到 JavaScript 时出现问题

标签 php javascript

我想将 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/

相关文章:

php - 如何开始阅读别人的代码?

javascript - observableArray 未定义

javascript - 如何在页面加载时返回一组随机的外部 xml 数据

php - 在 Elasticsearch 中将整个字符串与破折号匹配

PHPDocumentor 日期问题警告

php mysql认证问题

java - 你能从 javascript 读取 flash 吗?

javascript - 使用 Angularjs 的嵌套选项卡

javascript - 如何将每个数组元素插入另一个数组中的每个其他元素?

php - 如何在 PHP 中将 unicode 符号转换为 ascii 安全等价物