【发布时间】:2014-06-27 19:57:40
【问题描述】:
我目前正在做一个小型项目,我有 2 个 mysql 数据库表(问题和答案)。答案表包含 questionid。我在 ajax 调用中使用以下查询选择一个问题和 4 个相关答案,它可以工作但不确定它是否正确?
然后我将其作为数组传回以显示在我的网页上。正在显示问题,但没有显示答案,但我可以在控制台窗口的回复中看到值在那里。我在想可能是因为问题和答案在同一个数组中?
非常感谢任何帮助。
php/mysqli:
$sql= 'SELECT question FROM questions where difficulty = 1
UNION ALL
SELECT answer FROM answers a right join questions q on q.id = a.questionid WHERE q.difficulty = 1';
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
if($result->num_rows > 0){
$array = array(); // initialize
while($row = $result->fetch_array(MYSQLI_BOTH)){
$array[] = array(
'question' => $row[0],
'answer' => $row[1],
'answer' => $row[2],
'answer' => $row[3],
'answer' => $row[4]
);
}
}
header('Content-Type: application/json',true);
echo json_encode($array);
$result->free();
$mysqli->close();
Ajax 成功响应:
function response(json){
console.log(json);
var quest = json[0].question;
var ans1 = json[1].question;
var ans2 = json[2].question;
var ans3 = json[3].question;
var ans4 = json[4].question;
$("#questionBox").html('<h2>Q: ' + quest);
$("#answerBox").html('<h2>Q: ' + ans1);
}
Ajax 响应:
[{"question":"Is this an easy question?","answer":null},
{"question":"Yes","answer":null},
{"question":"No","answer":null},
{"question":"Maybe","answer":null},
{"question":"Who Knows","answer":null}]
直接从浏览器响应:
[{"question":"Is this an easy question?","answer":null},
{"question":"Yes","answer":null},
{"question":"No","answer":null},
{"question":"Maybe","answer":null},
{"question":"Who Knows","answer":null}]
【问题讨论】: