【发布时间】:2020-04-13 21:21:51
【问题描述】:
我正在使用 php 和 ajax 进行测验 webapp,单击单选按钮会触发一个函数,以使用 ajax 和 php 在数据库中获取新行,但是只要 ajax 成功,它就会在指定的 div 元素内输出对象对象调用。
这里是 ajax 方面的代码:
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var answer = $(this).val();
var question_id = $('#dataContainer').data('value');
$.ajax({
url:"quizengine.php",
method:"POST",
data:{
answer:answer,
question_id:question_id
},
dataType: 'json',
success:function(response){
console.info(response);
$('#question').text(response);
$('#answer_one').text(response);
$('#answer_two').text(response);
$('#answer_three').text(response);
}
});
});
});
</script>
这里是 php 部分的代码
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rubiqube";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
<?php
if (isset($_POST['answer'])) {
global $connection;
$answer = $_POST['answer'];
$question_id = $_POST['question_id'];
$result = mysqli_query($connection, "SELECT is_right FROM answers WHERE question_id='$question_id'");
$row = mysqli_fetch_assoc($result);
if (isset($row)) {
$correct = $row['is_right'];
if ($answer === $correct) {
$next = mysqli_query($connection, "SELECT Questions.question_id,Questions.lesson,Questions.instruction,Questions.question,Questions.image,Questions.option_type,Questions.question_value,Answers.answer_one,Answers.answer_two,Answers.answer_three,Answers.is_right FROM Questions LEFT JOIN Answers ON Questions.question_id = Answers.question_id WHERE Questions.question_id>'$question_id' ORDER BY Questions.question_id ASC LIMIT 1");
$nextrow = mysqli_fetch_assoc($next);
echo json_encode($nextrow);
exit();
}else{
echo "error";
exit();
}
}
}
?>
这是我正在谈论的图像 enter image description here
【问题讨论】:
-
JSON == JavaScript 对象表示法。你究竟期望得到什么?如果您想要对象中的特定元素,则必须访问该特定元素。
-
我想当 ajax 检索行时,它以文本格式将值输出到 id 为#question、#answer_one 等的 div
-
嗯,这不会神奇地发生。您必须完全按照您的需要创建输出。这里有很多关于如何使用 JavaScript 访问 JSON 元素的问题/答案。 stackoverflow.com/questions/10842841/… 或 stackoverflow.com/questions/18910939/… 或 stackoverflow.com/questions/41297161/… 之类的可能是一个不错的起点
-
好的,谢谢,我会试试这些链接