PHP函数更新未在JavaScript中调用的PHP变量

时间:2019-06-16 14:19:27

标签: javascript php mysqli

这可能是非常简单的,但是我想通过从SQL Server获取新的随机记录来更新PHP变量,然后将这些变量传递给JavaScript以使用它们,但是我调用的PHP函数仅能运行一次然后停止工作。我不知道函数调用或函数本身是否有问题。

<?php

function getQuestion(){
    $conn = mysqli_connect("localhost", "root", "pass", "projectDB");
    $sql = "SELECT question, answerA, answerB, answerC, answerD, 
    correctAns FROM questionTable ORDER BY rand() LIMIT 3";

    global $result, $row, $question, $answerA, $answerB, $answerC, 
    $answerD, $correctAns;

    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);
    $question = $row["question"];
    $answerA = $row["answerA"];
    $answerB = $row["answerB"];
    $answerC = $row["answerC"];
    $answerD = $row["answerD"];
    $correctAns = $row["correctAns"];

    mysqli_close($conn);
}

getQuestion();

?>
<script>
    var answerA = "<?php echo $answerA; ?>";
    var answerB = "<?php echo $answerB; ?>";
    var answerC = "<?php echo $answerC; ?>";
    var answerD = "<?php echo $answerD; ?>";
    var question = "<?php echo $question; ?>";
    var correctAnswer = "<?php echo $correctAns; ?>";

    function newQuestion(){

        <?php getQuestion(); ?>

        question = "<?php echo $question; ?>";
        answerA = "<?php echo $answerA; ?>";
        answerB = "<?php echo $answerB; ?>";
        answerC = "<?php echo $answerC; ?>";
        answerD = "<?php echo $answerD; ?>";
        correctAnswer = "<?php echo $correctAns; ?>";
    }

    else if (targetHit == true){ 
    reset(); 
    newQuestion();
    tick = 0;
    }
</script>

第一次定义变量并在顶级PHP中使用getQuestion()时,它们将获得正确的值,而第一次调用newQuestion()时,它们将使用不同的正确值进行更新,但是此后,调用newQuestion() )不会像应有的那样更改任何值。 谢谢。

1 个答案:

答案 0 :(得分:0)

这不是在javascript中编写php代码的正确方法,即使我们不应该在javascript中编写php代码也是如此。更好地通过ajax请求从数据库中检索值并将值存储在javascript变量上。它每次都会给您sql结果。 制作一个php文件来检索数据,并制作另一个php或js文件来进行ajax请求。 这是

的代码

所写的php文件

function getQuestion(){
$conn = mysqli_connect("localhost", "root", "pass", "projectDB");
$sql = "SELECT question, answerA, answerB, answerC, answerD, 
correctAns FROM questionTable ORDER BY rand() LIMIT 3";

global $result, $row, $question, $answerA, $answerB, $answerC, 
$answerD, $correctAns;

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_assoc($result);
$question = $row["question"];
$answerA = $row["answerA"];
$answerB = $row["answerB"];
$answerC = $row["answerC"];
$answerD = $row["answerD"];
$correctAns = $row["correctAns"];
mysqli_close($conn);
return $correctAns;}
echo json_encode(getQuestion());

此处ajax请求获取结果

$.ajax({
        type: 'post',
        url: 'phpfilename.php',
        success: function ( data ) {
          alert(JSON.parse(data));
        },
         error:function(error){
             console.log(error);
           }
      });