尝试提出问题并回答网页上的选项,该网页将从数据库中检索问题数据。 js对象的var如下所示:
var questions = [{
question: "What is 2*5?",
choices: [2, 5, 10, 15, 20],
correctAnswer: 2
},...
虽然我可以让这些只有一定数量的问题,但我想让它更有活力。
这就是我目前所写的:
<script type="text/javascript">
var questions = [
<?php
include "functions/connect.php";
$selqq="select * from quiz_question where QUIZ_ID=2";
$runqq=mysqli_query($con,$selqq);
while($rowqq=$runqq->fetch_array())
{
echo "{ question: '".$rowqq['QUESTION']."',
choices: [".$rowqq['CHOICE0'].",".$rowqq['CHOICE1'].",".$rowqq['CHOICE2'].",".$rowqq['CHOICE3']."],
correctAnswer: ".$rowqq['ANSWER']."},";
}
?>];
</script>
这对我不起作用,也许是因为“,”接近结尾,并将其置于开头也会这样做。 如何制作它以便我可以在数组中放置任意数量的对象?有可能吗?
答案 0 :(得分:0)
像这样更改脚本代码
<script type="text/javascript">
var questions =
<?php
$data = null;
$i = 0;
include "functions/connect.php";
$selqq="select * from quiz_question where QUIZ_ID=2";
$runqq=mysqli_query($con,$selqq);
while($rowqq=$runqq->fetch_array())
{
$data[$i]['question'] = $rowqq['QUESTION'];
$data[$i]['choices'] = $rowqq['CHOICE0'].$rowqq['CHOICE1'].$rowqq['CHOICE2'].$rowqq['CHOICE3'];
$data[$i]['correctAnswer'] = $rowqq['ANSWER'];
$i++;
}
echo json_encode($data);
?>
</script>