前端頁面包含 4 道單選題,每題一組 radio 按鈕,需收集用戶選中的選項值,通過 AJAX 異步提交至 JSP/Servlet 後台處理(如評分、入庫)。
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function submitAnswers() {
// 1. 定義數組收集答案
var answers = [];
// 2. 遍歷所有 name 為 "q" 開頭的 radio 組,取選中值
// 假設 HTML 結構:name="q1", name="q2", name="q3", name="q4"
for (var i = 1; i <= 4; i++) {
var val = $('input[name="q' + i + '"]:checked').val();
if (val === undefined) {
alert("第 " + i + " 題未作答!");
return; // 阻止提交
}
answers.push({ questionId: i, answer: val });
}
// 3. AJAX 提交
$.ajax({
type: "POST",
url: "<%=request.getContextPath()%>/exam/submit", // 後台接口
contentType: "application/json; charset=utf-8", // 發送 JSON
data: JSON.stringify({ answers: answers }), // 序列化為 JSON 字符串
dataType: "json", // 預期返回 JSON
success: function(resp) {
if (resp.code === 200) {
alert("提交成功,得分:" + resp.data.score);
// 跳轉結果頁或刷新
} else {
alert("提交失敗:" + resp.msg);
}
},
error: function(xhr, status, err) {
console.error(err);
alert("網絡異常,請重試");
}
});
}
</script>
<div class="question">
<p>1. Java 語言的跨平台性依賴於?</p>
<label><input type="radio" name="q1" value="A"> A. JVM</label>
<label><input type="radio" name="q1" value="B"> B. JDK</label>
<label><input type="radio" name="q1" value="C"> C. JRE</label>
<label><input type="radio" name="q1" value="D"> D. JAR</label>
</div>
<!-- q2, q3, q4 同理 -->
<button type="button" onclick="submitAnswers()">提交試卷</button>
@PostMapping("/exam/submit")
@ResponseBody
public Result submitExam(@RequestBody ExamSubmitDTO dto) {
List answers = dto.getAnswers();
// 1. 校驗數據完整性
// 2. 查詢標準答案(從 DB/Redis 獲取)
// 3. 計算得分
int score = 0;
for (AnswerDTO ans : answers) {
String correct = answerKeyMap.get(ans.getQuestionId());
if (correct != null && correct.equals(ans.getAnswer())) score += 25;
}
// 4. 保存記錄
examRecordService.save(userId, answers, score);
return Result.ok("提交成功").data("score", score);
}
// DTO 類
@Data
public class ExamSubmitDTO {
private List answers;
}
@Data
public class AnswerDTO {
private int questionId;
private String answer;
}
name="q{index}" 區分題組,:checked 取選中項,.val() 取值。[{questionId, answer}, ...],後台直接映射 DTO,避免字符串拼接解析麻煩。contentType: application/json + JSON.stringify,配合 @RequestBody 實現類型安全綁定。