【问题标题】:How to call and get response with Ajax如何使用 Ajax 调用并获得响应
【发布时间】:2013-10-10 23:48:51
【问题描述】:

我正在为我的互联网软件开发课程制作自己的网站。我是网络编码的新手。我熟悉 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.";
    }
}
?>

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

questions (question_id, question_name, answer1, answer2, answer3, answer4, answer [正确答案写为 1,2,3, or 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.';
}

?>

【问题讨论】:

  • 显示使用 AJAX 的失败尝试之一,以便我们帮助您修复它。我们不会从头开始为您编写代码。
  • 对不起。我添加了几乎效果最好的代码;我认为这可能是最有帮助的。不幸的是,这不包括我使用 Ajax 的任何尝试,这对我来说并不是一个问题,可能是因为我在这个网站上花费了这么多时间,严重缺乏睡眠。我在帖子末尾添加了 AJAX 尝试。
  • 你真的认为有人会阅读你凌乱、过时的代码并为你修复它吗?
  • @Panique-我没有要求有人来修复它。我寻求帮助。我不在乎这是否以一般提示、网站链接或代码的形式出现。坦率地说,我不在乎是否有人阅读了我所有的代码。我只是想提供足够的信息,以便有人可以为我指明正确的方向。至于它“凌乱”和“过时”,我确实说过我已经这样做了两个星期。如果它太乱了,我很抱歉,但你不必阅读它。至于它已经过时了,如果你能做一些有价值的事情并解释它是什么原因,那就太好了。

标签: javascript php jquery html ajax


【解决方案1】:

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

首先,不要在getNewQuestion() 中定义全局变量,您应该返回an array,然后执行$questionDetails = getNewQuestion(); 之类的操作,然后您可以访问$questionDetails['question'] 之类的各种属性。事实上,你对return 的使用是有缺陷的,在第一次return 调用之后,其他的都不会运行。您能够访问变量的唯一原因是您将它们设为全局变量。

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

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

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

【讨论】:

  • 非常感谢!这正是我所需要的!这清楚地解释了我需要做什么。我的代码现在很好用!真是太感谢你了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多