简体   繁体   English

如何使用JS从表单向JSON数组文件添加元素

[英]How to add an element to a JSON array file from a form using JS

I have this html form to add data to a json array file 我有这个HTML表单将数据添加到JSON数组文件中

<head>
        <script type="text/javascript" src="require.js"></script>
        <script type="text/javascript" src="AddBook.js"></script>
    </head>
    <body>
        <form id="add">
            <input type="text" id="isbn" name="isbn">
            <br>
            <input type="text" id="title" name="title">
            <br>
            <input type="text" id="author" name="author">
            <br>
            <input type="text" id="issued" name="issued">
            <br>
            <input type="submit" name="submit">
        </form>
        <script>
                var x = document.getElementById("add");
                var isbn = x.elements[0].value;
                var title = x.elements[1].value;
                var author = x.elements[2].value;
                var issued = x.elements[3].value;
                write(isbn,title,author,issued);
        </script>

and below is the AddBook.js 下面是AddBook.js

function write(isbn, title, author, issued) {
  const fs = require(['fs'], function (fs){  
  const data = fs.readFileSync('js/book.json');
  let jsonStr = data.toString();
  const obj = JSON.parse(jsonStr);

  obj.books.push({
    isbn,
    title,
    author,
    issued,
  });
  jsonStr = JSON.stringify(obj);
  console.log(jsonStr);
  fs.truncate('js/book.json', 0, () => {
    fs.writeFile('js/book.json', jsonStr, (err) => {
      if (err) {
        throw new Error(`Error writing file: ${err}`);
      }
    });
  });
  });
}

The problem is that the below script works as a standalone file but stops working as soon as it is used with the HTML. 问题在于下面的脚本可以作为独立文件使用,但是一旦与HTML一起使用便停止工作。 How can I make this script work with the form 如何使此脚本与表单一起使用

Try adding a function to run on the submission on your form. 尝试添加函数以在表单上的提交上运行。 Something like this: 像这样:

<head>
    <script type="text/javascript" src="require.js"></script>
    <script type="text/javascript" src="AddBook.js"></script>
    <script>
        function writeToJSON(){
            var x = document.getElementById("add");
            var isbn = x.elements[0].value;
            var title = x.elements[1].value;
            var author = x.elements[2].value;
            var issued = x.elements[3].value;
            write(isbn,title,author,issued);
        }
    </script>
</head>
<body>
    <form id="add" onsubmit="writeToJSON()">
        <input type="text" id="isbn" name="isbn">
        <br>
        <input type="text" id="title" name="title">
        <br>
        <input type="text" id="author" name="author">
        <br>
        <input type="text" id="issued" name="issued">
        <br>
        <input type="submit" name="submit">
    </form>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM