javascript - 如何保存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 文件。
安全不是问题。
解决方案
你可以这样...
<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 文件是一项复杂而敏感的任务,您可以对此进行更多探索,上面的代码只是一个示例,可能不合适。
建议:-
- 不要尝试更新包含
php
脚本的文件,为什么。?因为document.documentElement.innerHTML;
只会让你得到你的frontend
页面,这在更新实际的后端文件时是有风险的。 - 将所有/可更新/可编辑文件{仅包含前端视图}保存在单独的文件夹中,并进行相应更改,并在保存/更改/重新加载时将这些文件包含到您的页面中。
- 尽量将前端和后端脚本分开。
如有任何疑问,请发表评论。
推荐阅读
- python - Python:从 arg 解析器到字典
- django - 嵌套序列化程序的 Yasg 模式生成显示不正确的请求/响应
- vue.js - Vue SSR 子级别路由
- python - 使用熊猫有条件地移动列中的数据
- c++ - 如何在 DevC++ 中访问 Zlib.h?
- node.js - Readline操作的Node JS代码说明
- javascript - 为什么我在 addEventListener 中的函数只执行所写内容的一部分?
- cuda - Cuda min warp reduction 产生竞争条件
- image - 图像不显示在 reStructuredText (.rst) - HTML - 在 VS Code 中预览
- html - 使用 2 个文本框,输入一个文本框后如何禁用文本框