如何使用JavaScript点击按钮将数据推送到本地JSON文件



index.html

<button click="submit_data" id="submit">Submit</button>

script.js

document.getElementById('submit').addEventListener('click', function () {
task = document.getElementById('new_task').value
task_deadline = document.getElementById('task_deadline').value
let push_data = {
"item": task,
"deadline": task_deadline
}
// FileSystem.writeFile("data.json", JSON.stringify(push_data));
})

我在同一目录中有一个json文件,我正试图将push_data推送到该文件,但似乎找不到解决方案。我没有使用任何框架,比如Angular或React。是否可以使用纯javascript?如果没有,可能的解决方案是什么?

您只需要使用为此目的设计的API

https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API#writing_to_files

async function saveFile(blob) {
// create a new handle
const newHandle = await window.showSaveFilePicker();
// create a FileSystemWritableFileStream to write to
const writableStream = await newHandle.createWritable();
// write our file
await writableStream.write(blob);
// close the file and write the contents to disk.
await writableStream.close();
}
function save () {
let push_data = {
"item": "test",
"deadline": "test2"
}
saveFile(JSON.stringify(push_data)).then(console.log).catch(console.error); 
}
save();

注:

这个API打开了web一直缺乏的潜在功能。尽管如此,在设计API时,安全性一直是最令人关注的问题,除非用户特别允许,否则不允许访问文件/目录数据

您可以创建一个要下载的URL。数据URL。另请参阅工作小提琴

var storageObj = {
"hello": "world"
}
function download_json() {
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.querySelector('.dummy');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();
}
Click to download JSON on a non-sandbox environment 
<form onsubmit="download_json(); return false">
<button click="submit_data" id="submit">Submit</button>
</form>
<a class="dummy"></a>

最新更新