假设我有一个包含表单和输入以及提交按钮的 HTML 文档。
我想要发生的是,每次用户单击该提交按钮时,它都会生成一个包含表单数据的 JSON 文件,无需使用 Node.js 或 服务器。
如果这是一个愚蠢的问题,我很抱歉;这只是我的导师给我的作业。基本上,我拥有的是一个带有嵌入式脚本的 HTML 文件。这就像一个在线商店概念,用户凭据在表单上输入,然后生成一个包含该数据的 JSON 文件。
最佳答案
似乎每个人都忘记了 blob目的。这是一个例子。由于 stack overflow 的演示工具的工作方式,这可能很奇怪。希望对您有所帮助!
编辑:
根据评论,我意识到不是这样,而是我的代码。
您只需将 blob 的类型从 application/json
更改为 octet/stream
并添加一个下载属性(注意:这是 html5)和 tah dah!它有效。
function convertToJSON() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var email = document.getElementById('email').value;
var jsonObject = {
"FirstName": firstname,
"LastName": lastname,
"email": email
}
document.getElementById('output').value = JSON.stringify(jsonObject)
}
function saveToFile() {
convertToJSON();
var jsonObjectAsString = document.getElementById('output').value;
var blob = new Blob([jsonObjectAsString], {
//type: 'application/json'
type: 'octet/stream'
});
console.log(blob);
var anchor = document.createElement('a')
anchor.download = "user.json";
anchor.href = window.URL.createObjectURL(blob);
anchor.innerHTML = "download"
anchor.click();
console.log(anchor);
document.getElementById('output').append(anchor)
}
<br>First Name: <input id="firstname" value="John">
<br>Last Name:<input id="lastname" value="Pavek">
<br>Email:<input id="email" value="Example@example.com">
<br>
<button onclick="convertToJSON()">Convert</button>
<button onclick="saveToFile()">Save</button>
<hr> output: <br>
<textarea id="output"></textarea>
关于javascript - 如果没有 Node.js 或运行服务器,是否可以使用纯 JavaScript 通过 HTML 应用程序创建/输出 JSON 文件到硬盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199781/