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

PHP + AJAX 實現文章自動儲存草稿功能

     編輯:PHP 綜合知識

功能流程

  1. 編輯頁面載入,啟動倒計時(預設 60 秒)。
  2. 用戶輸入標題/內容時,重置倒計時。
  3. 倒計時歸零 → 觸發 AJAX POST 將標題、內容、時間戳送至後端。
  4. 後端驗證非空後存入草稿表(或 Session/檔案),返回成功/失敗標記。
  5. 前端顯示「儲存成功」並提供「載入草稿」按鈕。
  6. 用戶可手動點擊「載入草稿」恢復編輯,或「清除草稿」。

前端核心代碼

<!-- HTML -->
<input id="title" placeholder="標題">
<iframe id="editor" name="Editor" src="editor.html"></iframe>
<div id="autosave_status">60秒</div>
<a id="autosave_ctrl" href="javascript:;" onclick="startTimer()">開始計時</a>
<div id="draft_box"></div>

<script>
let timerId, countdown = 60;

function countdownTick(sec) {
    clearTimeout(timerId);
    document.getElementById('autosave_status').innerText = sec + '秒';
    if (sec > 0) {
        timerId = setTimeout(() => countdownTick(sec - 1), 1000);
    } else {
        const title = document.getElementById('title').value.trim();
        if (title) autoSavePost();
        else document.getElementById('autosave_status').innerText = '無需儲存';
    }
}

function autoSavePost() {
    const title = document.getElementById('title').value;
    const content = window.frames['Editor'].document.body.innerHTML; // 視編輯器而定
    const postTime = document.getElementById('postTime').value;
    const data = new URLSearchParams({title, content, postTime, act: 'autosave'});
    fetch('ajax.php', {method: 'POST', body: data})
        .then(r => r.text())
        .then(txt => {
            const box = document.getElementById('autosave_status');
            if (txt.includes('autosave_ok')) {
                box.innerText = '儲存成功,可載入草稿';
                loadDraft();
            } else if (txt.includes('autosave_error')) {
                box.innerText = '無內容,無需儲存';
            }
        });
}

function loadDraft() {
    fetch('ajax.php?act=loaddraft')
        .then(r => r.text())
        .then(html => document.getElementById('draft_box').innerHTML = html);
}

function clearDraft() {
    fetch('ajax.php?act=cleardraft', {method: 'POST'})
        .then(r => r.text())
        .then(html => document.getElementById('draft_box').innerHTML = html);
}

function startTimer() { countdownTick(60); }
function stopTimer() { clearTimeout(timerId); }
</script>

後端 ajax.php 關鍵邏輯

<?php
session_start();
$act = $_GET['act'] ?? $_POST['act'] ?? '';

switch ($act) {
    case 'autosave':
        $title = trim($_POST['title'] ?? '');
        $content = $_POST['content'] ?? '';
        if ($title === '' && $content === '') {
            exit('<autosave_error>無內容</autosave_error>');
        }
        // 存入資料庫/Session/檔案
        $_SESSION['draft'] = [
            'title' => $title,
            'content' => $content,
            'time' => $_POST['postTime'] ?? time(),
        ];
        exit('<autosave_ok>儲存成功</autosave_ok>');

    case 'loaddraft':
        $d = $_SESSION['draft'] ?? null;
        if ($d) {
            echo "<button onclick=\"restoreDraft()\">載入草稿 ({$d['time']})</button>";
            echo "<script>function restoreDraft(){document.getElementById('title').value='".addslashes($d['title'])."'; window.frames['Editor'].document.body.innerHTML='".addslashes($d['content'])."';}</script>";
        } else {
            echo '無草稿';
        }
        break;

    case 'cleardraft':
        unset($_SESSION['draft']);
        echo '草稿已清除';
        break;
}

關鍵技術點

點說明
編輯器取值範例用 `