萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 操作 JSON 資料 CRUD 完整實作教學

場景說明

前端以陣列物件 jsonObj.teacher 模擬後端資料,實作 Create/Read/Update/Delete 並即時同步至 HTML 表格。

資料結構

const jsonObj = {
    teacher: [
        { id: '1', name: 'Eric',   sex: 'm', age: '40' },
        { id: '2', name: 'Ghost',  sex: 'm', age: '28' },
        { id: '3', name: 'Didi',   sex: 'm', age: '27' }
    ]
};

核心功能模組

1. 重新渲染表格 refresh()

function refresh() {
    const $tbody = $("#personform tbody").empty(); // 假設表格有 tbody
    jsonObj.teacher.forEach(person => {
        const $tr = $(`
            <tr>
                <td>${person.id}</td>
                <td>${person.name}</td>
                <td>${person.sex}</td>
                <td>${person.age}</td>
                <td><a href="#" class="del-btn" data-id="${person.id}">刪除</a></td>
                <td><a href="#" class="edit-btn" data-id="${person.id}">編輯</a></td>
            </tr>
        `);
        $tbody.append($tr);
    });
}

2. 新增 addperson()

function addperson() {
    const id = $("#userid").val().trim();
    const name = $("#username").val().trim();
    const sex = $("#sex").val().trim();
    const age = $("#age").val().trim();

    if (!id || !name || !sex || !age) return alert("請填寫完整資料");
    if (jsonObj.teacher.some(p => p.id === id)) return alert("ID 已存在");

    jsonObj.teacher.push({ id, name, sex, age });
    refresh();
    clearAddForm();
}

3. 刪除 deleteperson(id)

$(document).on("click", ".del-btn", function(e) {
    e.preventDefault();
    if (!confirm("確定刪除?")) return;
    const id = $(this).data("id");
    jsonObj.teacher = jsonObj.teacher.filter(p => p.id !== id);
    refresh();
});

4. 編輯 - 回填表單 updateperson(id)

$(document).on("click", ".edit-btn", function(e) {
    e.preventDefault();
    const id = $(this).data("id");
    const person = jsonObj.teacher.find(p => p.id === id);
    if (!person) return;

    $("#update_userid").val(person.id).prop("disabled", true); // ID 不可改
    $("#update_username").val(person.name);
    $("#update_sex").val(person.sex);
    $("#update_age").val(person.age);
    // 捲動到編輯區或開啟 Modal
});

5. 更新儲存 update()

function update() {
    const id = $("#update_userid").val();
    const name = $("#update_username").val().trim();
    const sex = $("#update_sex").val().trim();
    const age = $("#update_age").val().trim();

    if (!name || !sex || !age) return alert("請填寫完整資料");

    const idx = jsonObj.teacher.findIndex(p => p.id === id);
    if (idx !== -1) {
        jsonObj.teacher[idx] = { id, name, sex, age };
        refresh();
        clearEditForm();
    }
}

完整 HTML 架構

<form id="addForm">
    <input type="text" id="userid" placeholder="ID">
    <input type="text" id="username" placeholder="姓名">
    <input type="text" id="sex" placeholder="性別">
    <input type="text" id="age" placeholder="年齡">
    <button type="button" onclick="addperson()">新增</button>
</form>

<table id="personform" border="1">
    <thead><tr><th>ID</th><th>姓名</th><th>性別</th><th>年齡</th><th>刪除</th><th>編輯</th></tr></thead>
    <tbody></tbody>
</table>

<form id="editForm" style="display:none; margin-top:20px; padding:10px; border:1px dashed #ccc;">
    <h4>編輯資料</h4>
    <input type="text" id="update_userid" disabled placeholder="ID">
    <input type="text" id="update_username" placeholder="姓名">
    <input type="text" id="update_sex" placeholder="性別">
    <input type="text" id="update_age" placeholder="年齡">
    <button type="button" onclick="update()">更新</button>
    <button type="button" onclick="clearEditForm(); $('#editForm').hide()">取消</button>
</form>

關鍵 jQuery 技巧總結

技巧說明
.data("id")讀取 data-id 屬性,自動轉型,比 .attr() 更乾淨。
.on("click", ".btn", fn)事件委派,動態新增的列也生效,無需重新綁定。
.empty() + .append()重渲染表格前清空舊內容,避免重複累積。
模板字面量 `...${var}...`ES6 語法,拼接 HTML 更易讀 (需確保環境支援或經 Babel 轉譯)。
.prop("disabled", true)設定屬性屬性 (Property) 而非 Attribute,正確控制表單元素狀態。

現代化遷移建議 (Vue/React/Vanilla)

  • 資料驅動視圖:以陣列為單一真實來源,UI 由框架自動衍生,無需手動 refresh()。
  • 狀態管理:集中管理 teacher 陣列,CRUD 透過 Mutation/Action 修改。
  • 表單驗證:使用 vee-validate (Vue) / react-hook-form (React) / 原生 Constraint Validation API。
  • API 整合:將 push/filter/findIndex 替換為 fetch/axios 呼叫後端 REST API。

總結

本範例展示了 jQuery 時代經典的「資料陣列 + 手動渲染 + 事件委派」模式。理解這套邏輯有助於維護舊專案,也能幫助理解現代框架「單向資料流」背後的核心概念:State → View、Event → State Update → View Re-render。

copyright © 萬盛學電腦網 all rights reserved