从用户添加到网页后获得的数据生成json文件

Generate a json file from data got after user adds it to the webpage

本文关键字:数据 文件 json 添加 用户 网页      更新时间:2023-09-26

我想把信息附加到json文件,当我的网页上做的事情。例如,当一个按钮点击,我想从我的文本区域的信息被添加到json"消息"字段。姓名和电子邮件也是一样。我如何使用JS/jQuery做到这一点?

var info = {};
showJSON();
function generateNewData(attribute) {
  info[attribute] = $('#' + attribute).val();
  showJSON();
}
function showJSON() {
  $('#json').html(
    JSON.stringify(info, null, 2)
  );
}
function downloadJSON() {
  saveData(info, 'my-json-filename.json');
}
function saveData(data, fileName) {
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
  
    let json = JSON.stringify(data, null, 2), // remove ', null, 2' if you don't want indentation
        blob = new Blob([json], { type: "octet/stream" }),
        url = window.URL.createObjectURL(blob);
  
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='name' onkeypress='generateNewData("name")'/>
<br />
<input type='email' id='email' onkeypress='generateNewData("email")'/>
<br />
<textarea id='message' onkeypress='generateNewData("message")'></textarea>
<pre id='json'></pre>
<button onClick='downloadJSON();'>Download JSON</button>

例如,如果我们想在用户写入新内容后生成一个JSON对象那么我们可以使用下面的代码片段。