點擊按鈕(同意/拒絕)時,取得該元素的 `name` 或 `id`,透過 AJAX 送至伺服器端控制器處理。
<button name="action" id="btnAgree" value="agree" class="action-btn">同意</button>
<button name="action" id="btnReject" value="reject" class="action-btn">拒絕</button>
<script>
document.querySelectorAll('.action-btn').forEach(btn => {
btn.addEventListener('click', async (e) => {
const target = e.currentTarget;
const payload = {
id: target.id,
name: target.name,
value: target.value
};
try {
const resp = await fetch('/api/handleAction', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
const result = await resp.json();
console.log('伺服器回應:', result);
} catch (err) {
console.error('請求失敗', err);
}
});
});
</script>
$('.action-btn').on('click', function() {
$.ajax({
url: '/api/handleAction',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
id: this.id,
name: this.name,
value: this.value
}),
success: res => console.log(res),
error: (xhr, status, err) => console.error(err)
});
});
@RestController
@RequestMapping("/api")
public class ActionController {
@PostMapping("/handleAction")
public Map handle(@RequestBody ActionDTO dto) {
// 業務邏輯
log.info("收到動作: id={}, name={}, value={}", dto.getId(), dto.getName(), dto.getValue());
return Map.of("code", 200, "msg", "處理成功");
}
static class ActionDTO {
private String id, name, value;
// getter/setter 省略
}
}
[HttpPost("api/handleAction")]
public IActionResult Handle([FromBody] ActionDto dto) {
_logger.LogInformation($"動作: {dto.Id}, {dto.Name}, {dto.Value}");
return Ok(new { code = 200, msg = "成功" });
}
public record ActionDto(string Id, string Name, string Value);
| 環節 | 重點 |
|---|---|
| 前端取值 | `e.currentTarget.id / name / value`,避免用 `this` 導致上下文錯誤 |
| 資料格式 | 統一用 JSON,`Content-Type: application/json` |
| 後端接收 | 對應 DTO/Record 自動繫結,勿用 `request.getParameter` 接收 JSON |
| 跨域 | 前後端分離需配置 CORS |
btn.disabled = true;
btn.textContent = '處理中...';
try { await fetch(...); } finally { btn.disabled = false; btn.textContent = originalText; }
現代前後端分離架構下,**前端用 `fetch`/`axios` 送 JSON,後端用 `@RequestBody`/`[FromBody]` 接收 DTO** 是最標準、最易維護的做法。