[英]How to call and get response with Ajax
我正在為我的Internet軟件開發課程創建自己的網站。 我是Web編碼的新手。 我熟悉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,答案[寫為1,2、3或4的正確答案],category_id)
MembersAnswers(用戶,category_id,question_id,分數)
我已經搜索了該站點以嘗試找到所需的內容,但找不到任何內容。 我真的希望這里有人可以幫助我。 先感謝您。
編輯:我添加了幾乎最有效的代碼; 我認為這可能是最有用的。 不幸的是,這不包括我使用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來完成您正在描述的事情,而我會省略掉它,因為這只會增加復雜性。
首先,您應該返回一個數組 ,並執行類似$questionDetails = getNewQuestion();
,而不是在getNewQuestion()
中定義全局變量$questionDetails = getNewQuestion();
,您可以訪問各種屬性,例如$questionDetails['question']
。 實際上,您對return的使用是有缺陷的,因為在第一個return
調用之后,其他任何一個都不會運行。 您能夠訪問變量的唯一原因是使它們成為全局變量。
查看提交操作,將PHP放入<script>
元素時,您會遇到問題。 您無法執行此操作,因為PHP在服務器上運行,然后在所有PHP運行之后,該文件已加載到Web瀏覽器中。 然后,將在瀏覽器(即客戶端)中執行所有JavaScript。
人們執行此操作的一般方法是將操作設置為另一個PHP文件。 那將提交數據,然后您可以解析表單輸入(通常通過$ _POST )。 因此,讀入所有這些數據,可能還會執行另一個數據庫查詢,以根據問題ID獲得正確答案,並確定是對還是錯,然后呈現新問題和先前的答案。
通常,人們會在一個PHP文件中完成所有這些操作,其中文件的開頭包含檢查內容是否為表單提交(例如,類似if (!empty($_POST)) { . . . }
)。 如果是提交,則運行檢查答案。 在所有情況下,您都會顯示一個新問題,如果是提交的問題,則還可以顯示它們是對還是錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.