選擇馬匹下拉框後,性別、毛色文本框自動填充對應數據,數據來源為資料庫。
用戶選擇馬匹 → 前端監聽change事件 → AJAX發送馬匹ID → 後端查詢DB → 返回JSON → 前端填充表單
<select id="horseSelect">
<option value="">請選擇馬匹</option>
<option value="1">寶馬</option>
<option value="2">汗血寶馬</option>
</select>
<input type="text" id="gender" readonly>
<input type="text" id="color" readonly>
<script>
$('#horseSelect').change(function() {
var horseId = $(this).val();
if (!horseId) { $('#gender, #color').val(''); return; }
$.get('/api/horse/' + horseId, function(data) {
$('#gender').val(data.gender);
$('#color').val(data.color);
}).fail(function() {
alert('數據加載失敗');
});
});
</script>
@GetMapping("/api/horse/{id}")
@ResponseBody
public HorseInfo getHorse(@PathVariable Long id) {
return horseService.findById(id); // 查詢DB封裝為DTO
}
// DTO
public class HorseInfo {
private String gender; // 雄/雌
private String color; // 棗紅/栗色/黑色...
// getter/setter
}
Map<Id, Info>秒級響應$.ajax({...}).abort()