如何使用Ajax调用和获取响应

时间:2013-10-10 23:48:52

标签: javascript php jquery html ajax

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

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

不幸的是,我无法弄清楚如何做到这一点。我可以得到一个新问题,但我无法显示结果。到目前为止,我已经在这个网页上花了至少12个小时,而且我完全卡住了。我在google上花了不少时间,我想我需要使用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>

以下是我的functions.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,answer1,answer2,answer3,answer4,answer [正确答案写成1,2,3或4],category_id)

membersAnswers(user,category_id,question_id,score)

我搜索过该网站试图找到我正在寻找的东西,但我找不到任何东西。我真的希望有人可以帮助我。先感谢您。

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

这是我在trivia.php页面中添加的尝试工作Ajax的内容。这是在标题中添加的。

        <script type="text/javascript">
    function correctOrNot(){
        $.ajax({
            type: "POST",
            url: "getResult.php",
            data:   "answer1=" + document.getElementById("answer1").value +
                    "&answer2=" + document.getElementById("answer2").value +
                    "&answer3=" + document.getElementById("answer3").value +
                    "&answer4=" + document.getElementById("answer4").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.';
}

&GT;

1 个答案:

答案 0 :(得分:0)

你不需要AJAX来做你正在描述的事情,我会把它留下来,因为它会增加复杂性。

首先,不是在getNewQuestion()中定义全局变量,而应返回an array,并执行类似$questionDetails = getNewQuestion();的操作,并且可以访问$questionDetails['question']等各种属性。实际上,您对return的使用存在缺陷,因为在第一次return调用之后,其他任何一个都无法运行。您能够访问变量的唯一原因是您将它们设为全局变量。

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

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

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