首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 獲取按鈕/輸入框 name 或 id 並透過 AJAX 傳值到後端控制器

     編輯:程式設計綜合問答

核心需求

點擊按鈕(同意/拒絕)時,取得該元素的 `name` 或 `id`,透過 AJAX 送至伺服器端控制器處理。

前端實作(原生 JS + Fetch API)

<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>

jQuery 寫法(若專案已引用)

$('.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)
    });
});

後端控制器範例

Spring MVC / Spring Boot

@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 省略
    }
}

ASP.NET Core

[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** 是最標準、最易維護的做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved