我正在编写一个井字游戏并实现 Ajax 和 Php,这对我来说都是新的。我查看了其他一些讨论,但似乎找不到我的答案。我的 js 文件正在调用 php,而 php 又在调用数据库并提取问题和答案——用户必须回答问题才能轮到他/她。但是,我的程序会返回下一个问题的答案,而不是当前问题。
这是我的php:
$con = mysql_connect('localhost', '412ygutstei', '412ygutstei');
if ($con)
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$questionNum = $_POST['q_id'];
mysql_select_db("ygutstei_db", $con);
$result = mysql_query("SELECT q_id, question_type, text,description, answer FROM questions,questiontype WHERE q_id=".$questionNum."");
$row = mysql_fetch_array($result);
$question = $row['description']." ".$row['text']."?|".$row['answer'];
echo($question);
mysql_close($con);
我的js函数,它将调用php:
function countDown() {
var element = document.getElementById(elem);
element.innerHTML = secs;
if(secs == 15){
document.getElementById('playerDisplay').innerHTML= printEquation();
}
if(secs == 0){
clearInterval(clock);
turn++;
startTimer();
document.getElementById(answer).value = "";
}
else{
secs--;
}
}
var expect = ""; var randomQNumber; var correctAnswer; var askQuestion = "";
function printEquation(){
randomQNumber = randNumber(1,8);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var elements = xmlhttp.responseText.split("|");
//elements[0] = document.getElementById("question")
correctAnswer = elements[1];
expect = correctAnswer;
askQuestion = elements[0];
//alert(correctAnswer);
}
}
xmlhttp.open("POST","G_TicTacToe.php",true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send("q_id="+randomQNumber);
if(turn % 2 == 0){
return "X Plays: " + askQuestion + " = ";
}
else{
return "O Plays: " + askQuestion + " = ";
}
}
function matchAnswer(a) {
var b = document.getElementById(a).value;
document.getElementById(a).innerHTML = b;
if(expect.toUpperCase() == b.toUpperCase()){
clearInterval(clock);
answeredQuestion = true;
window.alert("Correct! ");
document.getElementById(a).value = "";
click();
}
else{
clearInterval(clock);
window.alert("Incorrect! The correct answer was: " + expect);
document.getElementById(a).value = "";
playerTurn();
startTimer();
}
调用 matchAnswer() 的 html 代码:
<input type="text" id="answer">
<button id="equals" onclick="matchAnswer('answer');";>Answer</button>
</div>
<div class="playerAnswer">
</div>
例如:如果输出是:X 播放:State1 的名称是什么?- 回答伊利诺伊州,它将返回下一个问题的答案,“我最喜欢的动物是什么? - 即企鹅。
任何建议将不胜感激。如果需要更多代码,请告诉我。