如何致电并获得Ajax的响应

How to call and get response with Ajax

本文关键字:Ajax 响应 何致电      更新时间:2023-09-26

我正在为我的互联网软件开发课程制作自己的网站。我是网络编码的新手。我熟悉Java和其他一些语言,但除了HTML,我对网站设计很陌生。两周前我开始使用PHP和Javascript,但到目前为止我已经学到了很多东西。无论如何,我的设计遇到了障碍。

让我先解释一下我的网站。我正在做一个琐事网站。用户将登录,SQL 查询将为用户提供一个他们尚未回答的问题,以及屏幕左侧的 4 个可能答案。当用户单击"提交"答案按钮时,我希望发生两件事:1(一个新问题显示在屏幕左侧,2(上一个问题的结果("正确"或"不正确。正确答案是..."(显示在屏幕右侧。

不幸的是,我不知道该怎么做。我可以显示一个新问题,但无法显示结果。到目前为止,我已经在这个网页上花了至少 12 个小时,我完全被困住了。我在谷歌上花了相当多的时间,我认为我需要使用 Ajax,但我不熟悉 Ajax,我所有使用它的尝试都惨遭失败。我将不胜感激你能给我的任何帮助。

这是我的琐事页面代码:

    <?php
ob_start();
include_once 'functions.php';
include 'header.php';

//Trivia category
$category = 1;
$user = $_SESSION['user'];
getNewQuestion($user, $category);

$postValue = $_POST['value'];

echo <<<_END
 <html lang="en">
 <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <title>Trivia</title>
        <!-- Add bootstrap -->
        <link href="bootstrap-3.0.0/dist/css/bootstrap.css" rel="stylesheet">
        <!-- Import jumbotron -->
        <link rel="bootstrap-3.0.0/examples/jumbotron/jumbotron.css" rel="stylesheet">
        <!-- Import custom CSS -->
        <link href="custom.css" rel="stylesheet">
_END;
?>
        <script>
        function reportError()
        {
        alert("Report question error option not yet available.");
        }
        </script>
        <script>
        function returnAnswer()
        {
            if ($postValue == $optionValue)
            {
            queryMysql("INSERT INTO membersAnswers (user, category_id, question_id, score)
                VALUES ('$user', '$category', '$newQuestion[question_id]', '1')");
            document.getElementById('result').innerHTML=='Correct!';
            $msg = 'Correct!';
            alert($msg);
            }
            else
            {
            queryMysql("INSERT INTO membersAnswers (category_id, question_id, score)
                VALUES ('$category', '$newQuestion[question_id]', '0')");
            document.getElementById('result').innerHTML=='Incorrect. Correct Answer: $correctAnswer.';
            $msg = 'Incorrect. Correct Answer: $correctAnswer.';
            alert($msg);
            }
            }

        </script>
<?php
echo <<<_END
 </head>
 <body>
 <div class="container"  STYLE="background-color:white;">
    <!-- Serves as wrapper for page content. -->
        <!-- Create title header at top of page -->
        <div class="jumbotron">
        <h1>Play</h1>  <!-- Header -->
        <h2>Test your knowledge against your friends and earn achievements!</h2>
        <p>This site is still in development.</p>
        </div>
  </div><!-- .container -->

<div class="container" STYLE="background-color:white;">
<div class="row">
<!------extra space on left--------------------------------------------------------------------------->
<div class="col-md-1"></div>
<!------question box ------------------------------------------------------------------------------------>
<div class="col-md-5" style="border: 2px solid black">
    <form class="form" id="form" method="post">
        <h3 class="questions" id="id">$question</h3>
        <br/>
    <div class="radio"   style="font-size: 20px;">
        <input type="radio" value="option1" name="option" id="1">$answer1<br/>
        <input type="radio" value="option2" name="option" id="2">$answer2<br/>
        <input type="radio" value="option3" name="option" id="3">$answer3<br/>
        <input type="radio" value="option4" name="option" id="4">$answer4<br/>
        <input type="radio" checked='checked' style='display:none' value="5" id="optionsRadios">
        <br/>

    </div>

<br/>
<button type="button" name="submitBtn" class="btn btn-primary" onclick="returnAnswer()">Submit Answer</button>
<br/><p>  </p>
<button type="button" name="errorBtn" class="btn btn-primary" onclick="reportError()">Report an error</button>
<br/><p>  </p>
<button type="submit" name="nextBtn" class="btn btn-primary" action="trivia.php">Next Question</button>
<br/><p>  </p>
</form>
</div> <!--End div class col-md-5 -->
<!------extra space in middle------------------------------------------------------------------------>
<div class="col-md-1"></div>
<!------answer box----------------------------------------------------------------------------------->
<div class="col-md-3" style="border: 2px solid black">
<h3>Previous Question:</h3>
<p id="result">$msg</p>
<p>  </p>
<button type="button" name="errorBtn" class="btn btn-primary" onclick="reportError()">Report an error</button>
<br/><p>  </p>
</div> <!--End div class col-md-3 -->
<!------extra space on right--------------------------------------------------------------------------->
<div class="col-md-1"></div>
_END;
?>

</div> <!--End div class row -->
<p></p> <!-- Add extra space below question border -->
</div> <!--End div class container -->

<!-- Import to use navbar -->
<script src="bootstrap-3.0.0/assets/js/jquery.js"></script>
<!-- Import to use dropdown list
<script src="bootstrap-3.0.0/js/dropdown.js"></script> -->
<!-- Import so that menu becomes mobile menu on smaller screens -->
<script src="bootstrap-3.0.0/dist/js/bootstrap.min.js"></script>
 </body>
</html>

这是我的函数的一部分.php代码,其中包含上述脚本中调用的"getQuestion"函数:

    <?php
$dbhost = 
$dbuser = 
$dbpass = 
$dbname = 
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());


function getNewQuestion ($user, $category)
{
    global $question;
    global $answer1;
    global $answer2;
    global $answer3;
    global $answer4;
    global $optionValue;
    global $question_id;
    $query = queryMysql("SELECT * FROM questions
                        LEFT JOIN membersAnswers
                        ON membersAnswers.user = '$user' AND questions.question_id = membersAnswers.question_id
                        WHERE membersAnswers.question_id IS NULL AND questions.category_id = '$category'
                        ORDER BY RAND()
                        LIMIT 1;");
if (mysql_num_rows($selectQuestion))
    {
    $newQuestion = mysql_fetch_array ( $query );
    $question = $newQuestion['question_name'];
    $answer1 = $newQuestion['answer1'];
    $answer2 = $newQuestion['answer2'];
    $answer3 = $newQuestion['answer3'];
    $answer4 = $newQuestion['answer4'];
    $question_id = $newQuestion['question_id'];
    if ($newQuestion['answer'] = '1')
    {
    $correctAnswer = $newQuestion['answer1'];
    $optionValue = "option1";
    }
    elseif ($newQuestion['answer'] = '2')
    {
    $correctAnswer = $newQuestion['answer2'];
    $optionValue = "option2";
    }
    elseif ($newQuestion['answer'] = '3')
    {
    $correctAnswer = $newQuestion['answer3'];
    $optionValue = "option3";
    }
    elseif ($newQuestion['answer'] = '4')
    {
    $correctAnswer = $newQuestion['answer4'];
    $optionValue = "option4";
    }
    return $question;
    return $answer1;
    return $answer2;
    return $answer3;
    return $answer4;
    return $optionValue;
    return $question_id;
}
else {
    echo "There are no more questions at the moment.";
    }
}
?>

我不确定此信息是否必要,但以下是两个相关表的字段:

问题(question_id、question_name、答案 1、答案 2、答案 3、答案 4、答案 [正确答案写为 1、2、3 或 4]、category_id(

成员答案(用户、category_id、question_id、分数(

我已经搜索了这个网站,试图找到我正在寻找的东西,但我找不到任何东西。我真的希望这里有人可以帮助我。提前谢谢你。

编辑:我添加了几乎效果最好的代码;我认为这可能是最有帮助的。不幸的是,这不包括我使用Ajax的任何尝试。

这是我在琐事.php页面中添加的内容,以尝试使用Ajax。这是在标题中添加的。

        <script type="text/javascript">
    function correctOrNot(){
        $.ajax({
            type: "POST",
            url: "getResult.php",
            data:   "answerswer1=" + document.getElementById("answerswer1").value +
                    "&answer2=" + document.getElementById("answerswer2").value +
                    "&answer3=" + document.getElementById("answerswer3").value +
                    "&answer4=" + document.getElementById("answerswer4").value +
                    "&optionValue=" + document.getElementById("optionValue").value +
                    "&postOption=" + $_POST['option'] +
                    "&user=" + $_SESSION['user'] +
                    "&category=" + '1' +
                    "&question_id=" + document.getElementById("question_id").value,
            dataType: "text",
            success: function(html){
                $("#result").html(html);
            }
        });
        }
</script>

这是getResult.php代码:

    <?php
include_once 'functions.php';
if ($postOption == $optionValue)
{

queryMysql("INSERT INTO membersAnswers (user, category_id, question_id, score)
    VALUES ('$user', '$category', '$question_id', '1')");
echo 'Correct!';
}
else
{
queryMysql("INSERT INTO membersAnswers (user, category_id, question_id, score)
    VALUES ('$user', '$category', '$question_id', '0')");
echo 'Incorrect. Correct Answer: $correctAnswer.';
}

?>

你不需要AJAX来做你所描述的事情,我会省略它,因为它只会增加复杂性。

首先,与其在getNewQuestion()中定义全局变量,不如返回一个数组,并执行类似 $questionDetails = getNewQuestion(); 的操作,并且可以访问各种属性,例如 $questionDetails['question'] 。 事实上,您对 return 的使用是有缺陷的,因为在第一次return调用之后,其他调用都不会运行。 您能够访问变量的唯一原因是您使它们成为全局变量。

查看提交时的操作,当您将 PHP 放入 <script> 元素时,您会遇到问题。 你不能这样做,因为 PHP 在服务器上运行,然后,在所有 PHP 运行之后,文件被加载到 Web 浏览器中。 然后,任何JavaScript都将在浏览器中执行,也称为客户端。

人们这样做的一般方法是将操作设置为另一个 PHP 文件。 这将提交数据,然后您可以解析表单输入(通常通过 $_POST(。 因此,读取所有这些数据,可能会执行另一个数据库查询以根据问题 ID 获得正确答案,并确定它是对还是错,然后呈现一个新问题和以前的答案。

通常,人们会在一个PHP文件中完成所有这些操作,其中文件的开头包含一个检查,以查看它是否是表单提交(例如if (!empty($_POST)) { . . . }(。 如果是提交,则运行检查答案的内容。 在所有情况下,您都会显示一个新问题,如果是提交,您也可以显示它们是对还是错。