首页 > 解决方案 > 如何保存html body php的当前状态

问题描述

我有一个带有 Sortable.js 的 html 网站。当用户重新排列列表并单击保存按钮时,我想保存正文的当前状态。我不希望它保存到本地存储,而是直接保存到托管文件,用新的重新排列版本替换正文 html。

<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>
</body>

我相信我想要实现的目标非常简单,可以使用 php 和 ajax 来完成,但我找不到任何直接答案。

目前只有一个 index.php 文件。

安全不是问题。

标签: javascriptphphtmlajaxjquery-ui-sortable

解决方案


你可以这样...

   <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' onclick="saveHTML()">save changes</button>
      </div>
    </body>

Java 脚本

function saveHTML(){
  var currentStateHTML = document.documentElement.innerHTML;
  console.log(currentStateHTML);//For debugging
  $.post("file.php", {type : "save", state : currentStateHTML},
     function(data, status){
        if(status == "success"){
          if(data == "saved"){
            location.reload();//which is index.php itself
          }
          else console.log("error");
        }
     }
  );
}

.php 文件

<?php
  if(isset($_POST['type'])){
     if($_POST['type'] == "save"){
        $html = $_POST['state'];
        if(file_put_contents("index.php", $html)){
           echo "saved";
           //The file got updated
        } 
        else "error";
     }
  }
?>

注意:-在您的案例中更新/擦除/附加到文件 html/php 文件是一项复杂而敏感的任务,您可以对此进行更多探索,上面的代码只是一个示例,可能不合适。

建议:-

  1. 不要尝试更新包含php脚本的文件,为什么。?因为document.documentElement.innerHTML;只会让你得到你的frontend页面,这在更新实际的后端文件时是有风险的。
  2. 将所有/可更新/可编辑文件{仅包含前端视图}保存在单独的文件夹中,并进行相应更改,并在保存/更改/重新加载时将这些文件包含到您的页面中。
  3. 尽量将前端和后端脚本分开。

如有任何疑问,请发表评论。


推荐阅读