【问题标题】:How to save current state of html body php如何保存html body php的当前状态
【发布时间】:2021-11-18 13:26:37
【问题描述】:

我有一个带有 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文件。

安全不是问题。

【问题讨论】:

    标签: javascript php html ajax jquery-ui-sortable


    【解决方案1】:

    你可以这样...

       <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. 尽量将前端和后端脚本分开。

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

    【讨论】:

    • 谢谢,这行得通。我只改变了'document.documentElement.innerHTML;'到'document.querySelector("html").outerHTML;'。因为它从我的 loom 扩展中添加了一些样式和 loom-containers。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2010-10-14
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多