本文展示一個完整的 **ExtJS 4/5/6 + PHP** 後端交互範例,涵蓋:Grid 列表顯示、分頁工具列、工具列按鈕(新增/修改/刪除/搜索)、彈窗表單驗證、AJAX 異步交互、JSON 資料格式規範。
<script type="text/javascript">
Ext.onReady(function() {
// 定義資料模型
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'pass', type: 'string'},
{name: 'sex', type: 'string'},
{name: 'email', type: 'string'}
],
idProperty: 'id'
});
// Store 配置:分頁、遠端排序、篩選
var store = Ext.create('Ext.data.Store', {
model: 'User',
pageSize: 16,
proxy: {
type: 'ajax',
url: 'api/users.php', // 統一 API 入口
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'total'
},
// 將分頁/排序/篩選參數自動轉為查詢字串
simpleSortMode: true,
filterParam: 'filters',
sortParam: 'sort',
directionParam: 'dir'
},
autoLoad: true,
remoteSort: true,
remoteFilter: true
});
// 性別渲染器
function renderSex(value) {
return value === 'male'
? "<span style='color:red;font-weight:bold;'>男</span>"
: "<span style='color:green;font-weight:bold;'>女</span>";
}
var grid = Ext.create('Ext.grid.Panel', {
title: '用戶管理系統',
store: store,
height: 500,
width: '100%',
frame: true,
columns: [
{xtype: 'rownumberer', width: 40},
{xtype: 'checkcolumn', header: '選擇', dataIndex: 'selected', width: 50},
{header: 'ID', dataIndex: 'id', width: 60, sortable: true},
{header: '用戶名', dataIndex: 'name', width: 120, sortable: true, editor: 'textfield'},
{header: '密碼', dataIndex: 'pass', width: 100, hidden: true}, // 預設隱藏敏感欄位
{header: '性別', dataIndex: 'sex', width: 80, sortable: true, renderer: renderSex},
{header: '電子郵箱', dataIndex: 'email', width: 200, sortable: true, flex: 1}
],
// 底部分頁工具列
bbar: Ext.create('Ext.toolbar.Paging', {
store: store,
displayInfo: true,
displayMsg: '顯示 {0} - {1} 筆,共 {2} 筆',
emptyMsg: '無資料'
}),
// 頂部工具列
tbar: [
{text: '新增用戶', iconCls: 'x-fa fa-plus', handler: addUser},
'-',
{text: '修改用戶', iconCls: 'x-fa fa-edit', handler: editUser, disabled: true},
'-',
{text: '刪除選中', iconCls: 'x-fa fa-trash', handler: deleteUsers, disabled: true},
'->',
{
xtype: 'textfield',
emptyText: '搜尋用戶名...',
enableKeyEvents: true,
listeners: {
keyup: function(field, e) {
if (e.getKey() === e.ENTER) {
store.getProxy().setExtraParam('search', field.getValue());
store.loadPage(1);
}
}
}
}
],
// 選取模型:啟用複選框
selModel: {
type: 'checkboxmodel',
mode: 'MULTI',
listeners: {
selectionchange: function(sm, selections) {
grid.down('#editBtn').setDisabled(selections.length !== 1);
grid.down('#deleteBtn').setDisabled(selections.length === 0);
}
}
},
renderTo: 'grid-container'
});
var formPanel = Ext.create('Ext.form.Panel', {
bodyPadding: 10,
fieldDefaults: {labelAlign: 'right', labelWidth: 80, anchor: '100%'},
defaultType: 'textfield',
items: [
{xtype: 'hidden', name: 'id'},
{fieldLabel: '用戶名', name: 'name', allowBlank: false, blankText: '用戶名不可為空'},
{fieldLabel: '密碼', name: 'pass', inputType: 'password', allowBlank: false},
{
xtype: 'radiogroup',
fieldLabel: '性別',
columns: 2,
allowBlank: false,
items: [
{boxLabel: '男', name: 'sex', inputValue: 'male', checked: true},
{boxLabel: '女', name: 'sex', inputValue: 'female'}
]
},
{fieldLabel: '郵箱', name: 'email', vtype: 'email', allowBlank: false}
]
});
var win = Ext.create('Ext.window.Window', {
title: '用戶資料',
closeAction: 'hide',
modal: true,
width: 400,
layout: 'fit',
items: [formPanel],
buttons: [
{text: '儲存', handler: saveUser},
{text: '取消', handler: () => win.hide()}
]
});
// 新增
function addUser() {
formPanel.getForm().reset();
win.setTitle('新增用戶');
win.show();
}
// 編輯
function editUser() {
var selection = grid.getSelectionModel().getSelection()[0];
if (selection) {
formPanel.loadRecord(selection);
win.setTitle('編輯用戶');
win.show();
}
}
// 刪除(批次)
function deleteUsers() {
var selections = grid.getSelectionModel().getSelection();
if (selections.length === 0) return;
Ext.Msg.confirm('確認刪除', `確定刪除 ${selections.length} 筆資料?`, function(btn) {
if (btn === 'yes') {
var ids = selections.map(r => r.get('id')).join(',');
Ext.Ajax.request({
url: 'api/users.php',
method: 'DELETE',
params: {ids: ids},
success: function(response) {
var result = Ext.decode(response.responseText);
if (result.success) {
store.reload();
Ext.toast('刪除成功');
} else {
Ext.Msg.alert('失敗', result.msg);
}
}
});
}
});
}
// 儲存(新增/更新自動判斷)
function saveUser() {
var form = formPanel.getForm();
if (!form.isValid()) return;
var record = form.getRecord() || Ext.create('User');
form.updateRecord(record);
var isNew = record.phantom;
var url = 'api/users.php';
var method = isNew ? 'POST' : 'PUT';
record.save({
url: url,
method: method,
success: function() {
win.hide();
store.reload();
Ext.toast(isNew ? '新增成功' : '更新成功');
},
failure: function(record, operation) {
Ext.Msg.alert('失敗', operation.getError().msg || '伺服器錯誤');
}
});
}
});
</script>
<?php
// api/users.php
header('Content-Type: application/json; charset=utf-8');
require_once 'db.php'; // PDO 連線
require_once 'auth.php'; // 權限驗證
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$params = array_merge($_GET, $_POST, $input ?? []);
try {
switch ($method) {
case 'GET':
handleList($pdo, $params);
break;
case 'POST':
handleCreate($pdo, $params);
break;
case 'PUT':
handleUpdate($pdo, $params);
break;
case 'DELETE':
handleDelete($pdo, $params);
break;
default:
http_response_code(405);
echo json_encode(['success' => false, 'msg' => 'Method Not Allowed']);
}
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'msg' => $e->getMessage()]);
}
function handleList(PDO $pdo, array $params) {
$page = max(1, (int)($params['page'] ?? 1));
$limit = max(1, min(100, (int)($params['limit'] ?? 16)));
$offset = ($page - 1) * $limit;
$search = $params['search'] ?? '';
$sort = $params['sort'] ?? 'id';
$dir = strtoupper($params['dir'] ?? 'ASC') === 'DESC' ? 'DESC' : 'ASC';
$where = '';
$bind = [];
if ($search) {
$where = "WHERE name LIKE :search OR email LIKE :search";
$bind[':search'] = "%{$search}%";
}
// 總數
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users {$where}");
$stmt->execute($bind);
$total = $stmt->fetchColumn();
// 分頁資料
$sql = "SELECT id, name, pass, sex, email FROM users {$where} ORDER BY {$sort} {$dir} LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$bind[':limit'] = $limit;
$bind[':offset'] = $offset;
$stmt->execute($bind);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'total' => $total, 'data' => $data]);
}
function handleCreate(PDO $pdo, array $data) {
$stmt = $pdo->prepare("INSERT INTO users (name, pass, sex, email) VALUES (:name, :pass, :sex, :email)");
$stmt->execute([
':name' => $data['name'],
':pass' => password_hash($data['pass'], PASSWORD_DEFAULT), // 密碼加密!
':sex' => $data['sex'],
':email' => $data['email'],
]);
echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
}
function handleUpdate(PDO $pdo, array $data) {
$id = $data['id'];
$fields = ['name', 'sex', 'email'];
$sets = [];
$bind = ['id' => $id];
foreach ($fields as $field) {
if (isset($data[$field])) {
$sets[] = "{$field} = :{$field}";
$bind[":{$field}"] = $data[$field];
}
}
if (isset($data['pass']) && $data['pass']) {
$sets[] = "pass = :pass";
$bind[':pass'] = password_hash($data['pass'], PASSWORD_DEFAULT);
}
if (empty($sets)) throw new Exception('無更新欄位');
$sql = "UPDATE users SET " . implode(', ', $sets) . " WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute($bind);
echo json_encode(['success' => true]);
}
function handleDelete(PDO $pdo, array $params) {
$ids = array_map('intval', explode(',', $params['ids'] ?? ''));
if (empty($ids)) throw new Exception('無效 ID');
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("DELETE FROM users WHERE id IN ({$placeholders})");
$stmt->execute($ids);
echo json_encode(['success' => true, 'deleted' => $stmt->rowCount()]);
}
?>
| 功能 | ExtJS 關鍵配置 | PHP 後端要點 |
|---|---|---|
| 分頁 | store.pageSize + PagingToolbar + remoteSort/remoteFilter | LIMIT/OFFSET + COUNT(*) 總數 |
| 排序 | columns.sortable + store.remoteSort | ORDER BY 動態欄位(需白名單驗證) |
| 搜尋 | Proxy extraParams + store.loadPage(1) | WHERE LIKE 參數化查詢 |
| 表單驗證 | allowBlank, vtype, blankText | 後端二次驗證(永不信任前端) |
| 批次刪除 | CheckboxModel + 選取陣列 ID 合併 | IN 查詢 + 參數化防注入 |
| 密碼安全 | inputType: 'password' | password_hash() / password_verify() |