萬盛學電腦網

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

jQuery + PHP + MySQL 實作 360 風格功能開關:完整前後端整合教學

功能概覽

類似 360 安全衛士的開關 UI:

  • 前端:單一圖片透過 background-position 切換開/關狀態
  • 互動:點擊開關 → AJAX POST 送至後台 → 更新資料庫 → 回傳結果 → 前端切換樣式
  • 體驗:滑鼠懸停列表高亮、按鈕狀態即時回饋、錯誤處理

資料庫設計

CREATE TABLE `pro` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(50) NOT NULL COMMENT '功能標題',
  `description` VARCHAR(200) NOT NULL COMMENT '功能說明',
  `status` TINYINT(1) NOT NULL DEFAULT '0' COMMENT '0=關閉, 1=開啟',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

前端頁面 (index.php)

<?php
require_once 'connect.php';
$query = $mysqli->query("SELECT * FROM pro ORDER BY id ASC");
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>功能開關管理</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <h1>系統功能開關</h1>
    <?php while ($row = $query->fetch_assoc()): ?>
      <div class="feature-item">
        <div class="feature-header">
          <h3><?= htmlspecialchars($row['title']) ?></h3>
          <span class="toggle-switch"
                data-id="<?= $row['id'] ?>"
                data-status="<?= $row['status'] ?>"
                role="switch"
                aria-checked="<?= $row['status'] ? 'true' : 'false' ?>"
                aria-label="<?= $row['status'] ? '關閉' : '開啟' ?> <?= htmlspecialchars($row['title']) ?>"
                title="<?= $row['status'] ? '點擊關閉' : '點擊開啟' ?>"></span>
        </div>
        <p><?= htmlspecialchars($row['description']) ?></p>
      </div>
    <?php endwhile; ?>
  </div>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="app.js"></script>
</body>
</html>

CSS 樣式 (style.css)

.container { max-width: 800px; margin: 40px auto; padding: 0 20px; }
.feature-item { 
  padding: 20px; border-bottom: 1px solid #eee; 
  position: relative; transition: background 0.2s; 
}
.feature-item:hover { background: #fffbe6; }
.feature-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.feature-header h3 { font-size: 16px; font-weight: 600; color: #2c3e50; margin: 0; }
.feature-item p { color: #666; line-height: 1.6; margin: 0; }

/* 開關按鈕 - 使用單一圖片 Sprite */
.toggle-switch {
  width: 64px; height: 32px;
  background: url('switch-sprite.png') no-repeat;
  cursor: pointer; border-radius: 16px;
  transition: background-position 0.2s, box-shadow 0.2s;
  flex-shrink: 0;
}
.toggle-switch.on { background-position: 0 0; box-shadow: inset 0 0 0 2px #27ae60; }
.toggle-switch.off { background-position: 0 -32px; box-shadow: inset 0 0 0 2px #ddd; }
.toggle-switch:focus { outline: 2px solid #3498db; outline-offset: 2px; }
.toggle-switch.loading { opacity: 0.6; pointer-events: none; }

/* Sprite 圖片說明:
   寬 64px,高 64px
   上半部 (0,0)    = 開啟狀態 (綠色背景、滑塊在右)
   下半部 (0,-32)  = 關閉狀態 (灰色背景、滑塊在左)
*/

前端邏輯 (app.js)

(function($) {
  'use strict';

  var $container = $('.container');
  var apiUrl = 'action.php';

  // 事件委派:動態新增項目也生效
  $container.on('click', '.toggle-switch', function(e) {
    e.preventDefault();
    var $switch = $(this);
    var id = $switch.data('id');
    var currentStatus = $switch.data('status');  // 0 或 1
    var newStatus = currentStatus === 1 ? 0 : 1;
    var actionType = newStatus === 1 ? 'enable' : 'disable';

    // UI 即時回饋:進入載入狀態
    $switch.addClass('loading');

    $.ajax({
      url: apiUrl,
      type: 'POST',
      dataType: 'json',
      data: { id: id, status: newStatus },
      success: function(resp) {
        if (resp.success) {
          // 更新資料屬性與 ARIA
          $switch.data('status', newStatus)
                 .attr('aria-checked', newStatus === 1)
                 .attr('title', newStatus === 1 ? '點擊關閉' : '點擊開啟')
                 .attr('aria-label', (newStatus === 1 ? '關閉' : '開啟') + ' 功能');
          
          // 切換視覺類別
          $switch.toggleClass('on off');
        } else {
          alert('操作失敗:' + (resp.message || '未知錯誤'));
          // 可選:搖晃動畫提示失敗
          $switch.addClass('shake');
          setTimeout(() => $switch.removeClass('shake'), 500);
        }
      },
      error: function(xhr) {
        alert('請求異常:' + (xhr.responseJSON?.message || xhr.statusText));
      },
      complete: function() {
        $switch.removeClass('loading');
      }
    });
  });

  // 滑鼠懸停列表高亮 (CSS :hover 已處理,JS 此處可擴充更複雜邏輯)
  // $container.on('mouseenter mouseleave', '.feature-item', function(e) {
  //   $(this).toggleClass('hover', e.type === 'mouseenter');
  // });

})(jQuery);

後端處理 (action.php)

<?php
require_once 'connect.php';

header('Content-Type: application/json; charset=utf-8');

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$status = isset($_POST['status']) ? (int)$_POST['status'] : 0;

if ($id <= 0 || ($status !== 0 && $status !== 1)) {
  http_response_code(400);
  echo json_encode(['success' => false, 'message' => '參數錯誤']);
  exit;
}

// 使用 Prepared Statement 防 SQL 注入
$stmt = $mysqli->prepare("UPDATE pro SET status = ? WHERE id = ?");
$stmt->bind_param('ii', $status, $id);
$result = $stmt->execute();

if ($result) {
  echo json_encode(['success' => true, 'status' => $status]);
} else {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => '資料庫更新失敗:' . $mysqli->error]);
}
$stmt->close();
$mysqli->close();

資料庫連線 (connect.php)

<?php
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
if ($mysqli->connect_errno) {
  die('資料庫連線失敗:' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');

安全性強化清單

  • ✅ Prepared Statements:防止 SQL 注入
  • ✅ 輸入驗證:強制轉型 (int)、驗證狀態值
  • ✅ 輸出編碼:htmlspecialchars() 防 XSS
  • ✅ CSRF 保護:建議加入 CSRF Token 驗證(表單隱藏欄位或 Header)
  • ✅ 權限檢查:實際專案需驗證使用者登入與權限
  • ✅ 錯誤資訊不外洩:生產環境隱藏 SQL 詳細錯誤

現代化改良建議

  1. Vue/React 重構:狀態管理更清晰,開關元件可複用
  2. API 規範化:RESTful 設計 PATCH /api/features/{id},回傳標準 JSON
  3. 樂觀鎖定:高併發場景加入 version 欄位防止覆蓋
  4. 操作日誌:記錄誰、何時、改了什麼狀態
  5. 批次操作:支援全選開啟/關閉、匯入匯出設定

總結

本範例展示了從資料庫設計、後端 API、前端樣式與互動邏輯的完整整合流程。核心技術點包括:CSS Sprite 開關動畫、AJAX 非同步更新、Prepared Statement 安全查詢、ARIA 無障礙屬性。這套模式廣泛應用於功能旗標、使用者偏好設定、內容審核狀態等場景,是全端開發者必備的基礎技能組合。

copyright © 萬盛學電腦網 all rights reserved