假设我有一个包含表单和输入的HTML文档以及一个提交按钮。
我想发生的是,每次用户单击该提交按钮时,它都会生成一个包含表单数据的 JSON 文件.js而无需使用 Node 或服务器。
如果这是一个愚蠢的问题,我很抱歉;这只是我的老师给我的作业。基本上,我有一个带有嵌入式脚本的 HTML 文件。这就像一个在线商店概念,其中包含在表单上输入的用户凭据,然后使用该数据生成 JSON 文件。
每个人似乎都忘记了 blob 对象。下面是一个示例。这可能很奇怪,因为堆栈溢出的演示工具的工作方式。我希望这有帮助!
编辑:
根据评论,我意识到不是这样,而是我的代码。您只需将 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>