是的,这是可能的,使用 jQuery 是最好的解决方案。
http://api.jquery.com/jQuery.ajax/
<?PHP
if (!empty($_GET['action']) && $_GET['action'] == 'ajax_check') {
// I a final solution you should load here the answer of the question from database by name
$answers = array(
'foo' => 1,
'baa' => 3,
);
// Prepare and default answer in error case
$return = array(
'message' => 'Invalud choise',
);
if (isset($answers[$_GET['name']])) {
// If question/answer was found in database, check if users chouse is correct
if ($answers[$_GET['name']] == $_GET['value']) {
$return['message'] = 'Correct answer';
} else {
$return['message'] = 'Wrong answer';
}
}
// Return answer to java script
header('Content-type: text/json');
echo json_encode($return);
die();
}
?>
Question 1
<input type="radio" name="foo" value="1" class="question_radio" />
<input type="radio" name="foo" value="2" class="question_radio" />
<input type="radio" name="foo" value="3" class="question_radio" />
<input type="radio" name="foo" value="4" class="question_radio" />
<br />
Question 2
<input type="radio" name="baa" value="1" class="question_radio" />
<input type="radio" name="baa" value="2" class="question_radio" />
<input type="radio" name="baa" value="3" class="question_radio" />
<input type="radio" name="baa" value="4" class="question_radio" />
<!-- Load jquery framework from google, dont need to host it by your self -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// When document was loadet succesfull
$(".question_radio").click(function () {
// Listen on all click events of all objects with class="question_radio"
// It is also possible to listen and input[type=radio] but this can produce false possitives.
// Start communication to PHP
$.ajax({
url: "test.php", // Name of PHP script
type: "GET",
dataType: "json", // Enconding of return values ²see json_encode()
data: { // Payload of request
action: 'ajax_check', // Tel PHP what action we like to process
name: $(this).attr('name'),
value: $(this).val(),
}
}).done(function(data) {
// Procces the answer from PHP
alert( data.message );
});
});
});
</script>