我不确定为什么在测验结束时(50秒前)和计时器结束时再次输出两次。这导致我的数据库出现问题,导致数据输入两次。我使用了预先编写脚本的jquery-1.9.1.min.js
和watch.js
。我在下面显示的代码是我编写的代码。计时器设定为50秒。这是我的问题的一个例子:
Output after: 20 sec Output after:50 sec
Answer: 3 Answer: 3
Wrong: 6 Wrong: 6
Unanswered: 4 Unanswered: 4
Score: 50 Score:50
Answer: 3
Wrong: 6
Unanswered: 4
Score: 50
的index.php
代码的第一部分是连接到数据库并调用表格中的所有数据进行测验,其中包括问题(每个答案4个答案)和一个"下一个"按钮。
//这里是计时器功能的地方
<div id="demo1" class="demo" style="text-align:center;font-size: 25px;">00:00:00</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/watch.js"></script>
<script>
$(document).ready(function(){
$('#demo1').stopwatch().stopwatch('start');
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i){
hider=i+2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
}
else if(count==i+1){
var step=i + 1;
//$("#next"+step).attr('type','submit');
$("#next"+step).on('click',function(){
submit();
});
}
else{
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit(){
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i){
var step = i + 1;
var step1 = i + 2;
$('#next'+step).on('click',function(){
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
setTimeout(function() {
submit();
}, 50000);
});
</script>
</body>
</html>
下一个文件ajax.php是我显示结果的地方,也是我遇到问题的地方。
$response=mysql_query("select id,question_name,answer from questions");
$i=1;
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
while($result=mysql_fetch_array($response)){
if($result['answer']==$_POST["$i"]){
$right_answer++;
}else if($_POST["$i"]==5){
$unanswered++;
}
else{
$wrong_answer++;
}
$i++;
}
echo "<div id='answer'>";
echo " Right Answer : <span class='highlight'>". $right_answer."</span><br>";
echo " Wrong Answer : <span class='highlight'>". $wrong_answer."</span><br>";
echo " Unanswered Question : <span class='highlight'>". $unanswered."</span><br>";
$total=$right_answer+$wrong_answer+$unanswered;
$score=($right_answer/$total)*100;
echo " Your Score : <span class='highlight'>". $score."</span> <br>";
echo "</div>";
$taken = 1;
//insert athlete score
$myscore = "INSERT INTO quiz_results (athlete, score, taken) VALUES ('$_SESSION[loginname]' , '$score', '$taken')";
echo "</br>";
$results= mysql_query($myscore,$con);
if($results)
echo "Score inputted";
答案 0 :(得分:0)
您正在调用提交功能两次:一次是当一个人点击下一个按钮,第二次是50秒后 - 独立于任何用户操作。只需计算submit()
次来电。
答案 1 :(得分:0)
由于用户点击最后一个“下一步”按钮,您应该在致电submit()
之前取消超时。
对setTimeout()
的调用会返回超时的ID。您可以使用它来取消超时。
var timeoutId = setTimeout(function() {
submit();
}, 50000);
然后,当用户回答最后一个问题并单击“下一步”按钮时:
clearTimeout(timeoutId);
submit();