You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP与AJAX保存HTML页面body的当前状态到服务器托管文件

单文件PHP+AJAX实现方案

整体逻辑全部写在同一个index.php文件里即可:前端监听保存按钮点击事件,读取当前页面body的完整HTML内容,通过AJAX提交给后端;后端收到内容后直接替换本地index.php中的对应body段即可。

完整可运行代码

你可以直接把下面的代码替换你原有的index.php内容使用:

<?php
// 后端处理逻辑:接收POST提交的body内容,写入文件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['body_content'])) {
    // 读取当前index.php的原始内容
    $original_content = file_get_contents(__FILE__);
    // 替换body部分的内容
    $new_content = preg_replace('/<body>[\s\S]*?<\/body>/', '<body>' . $_POST['body_content'] . '</body>', $original_content);
    // 写回文件
    file_put_contents(__FILE__, $new_content);
    // 返回成功响应
    echo 'success';
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>排序列表保存</title>
    <!-- 请自行将Sortable.js下载到本地后引入,避免使用外部链接 -->
    <script src="./Sortable.min.js"></script>
</head>
<body>
  <div class='wrapper'>
    <ul class='list'>
      <li class='item' contenteditable='true'>Item 1</li>
      <li class='item' contenteditable='true'>Item 2</li>
      <li class='item' contenteditable='true'>Item 3</li>
    </ul>
    <button class='add-item'>add new item</button>
    <button class='save'>save changes</button>
  </div>
  <script>
    // 初始化Sortable拖拽功能
    const list = document.querySelector('.list');
    new Sortable(list, {
        animation: 150,
        ghostClass: 'sortable-ghost'
    });
    // 添加新项按钮功能
    document.querySelector('.add-item').addEventListener('click', () => {
        const newItem = document.createElement('li');
        newItem.className = 'item';
        newItem.contentEditable = true;
        newItem.textContent = `Item ${list.children.length + 1}`;
        list.appendChild(newItem);
    });
    // 保存按钮点击事件
    document.querySelector('.save').addEventListener('click', async () => {
        const bodyContent = document.body.innerHTML;
        // 提交AJAX请求
        const res = await fetch(window.location.href, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `body_content=${encodeURIComponent(bodyContent)}`
        });
        const result = await res.text();
        if (result === 'success') {
            alert('保存成功');
        } else {
            alert('保存失败');
        }
    });
  </script>
</body>
</html>

注意事项

  • 请确保你的服务器对index.php文件有可写权限,Linux环境可以执行chmod 666 index.php临时赋予权限测试
  • 因不需要考虑安全问题,代码没有做XSS过滤、写入权限校验等逻辑,仅适合本地测试或者内部无公开访问的场景使用

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:45:03