【问题标题】:How can I put input value to the JSON in node.js file如何将输入值放入 node.js 文件中的 JSON
【发布时间】:2020-03-30 00:19:08
【问题描述】:

我正在制作 TODO 列表 Web 应用程序。

这是下面的“todo.html”代码:

<html>
<head>
  <title>My TODO List</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="main.css">
  <script>

    $(document).ready(function() {

      $("#submit").click(function() {
        var bla = $('#item').val();
        $("#todo").append("<li class='todoVal'>" + bla + "</li>");
      });

      // $(document).click(function(e) {
      //   if (e.target.className == 'todoVal') {
      //     var t = e.target.innerText
      //     $(e.target).remove();
      //     $("#completed").append("<li class='completedVal'>" + t + "</li>");
      //   }
      // });

      $(document).click(function(e) {
        if (e.target.className == 'completedVal') {
          $(e.target).remove();
        }
      });

      jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
        return this.each(function() {
          var clicks = 0,
            self = this;
          jQuery(this).click(function(event) {
            clicks++;
            if (clicks == 1) {
              setTimeout(function() {
                if (clicks == 1) {
                  single_click_callback.call(self, event);
                } else {
                  double_click_callback.call(self, event);
                }
                clicks = 0;
              }, timeout || 500);
            }
          });
        });
      }
      $(document).single_double_click(function(e) {
        if (e.target.className == 'todoVal') {
          var t = e.target.innerText
          $(e.target).remove();
          $("#completed").append("<li class='completedVal'>" + t + "</li>");
        }
      }, function(e) {
        if (e.target.className == 'todoVal') {
          $(e.target).remove();
        }
      });

      $("#clear").click(function() {
        $("li").remove();
      });

    });
  </script>
</head>

<body>
  <div id="addItem" class="box">
    Task:
    <input id="item" type="text" name="add_item" />
    <button id="submit" type="button">Add</button>
    <button id="clear" type="button">Clear All</button>
  </div>
  <div id="todo" class="box">
    <h4>TODO:</h4>
    <ul></ul>
  </div>
  <div id="completed" class="box">
    <h4>Completed:</h4>
    <ul></ul>
  </div>
</body>

</html>

这是下面的“app.js”文件:

var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require("body-parser");

// middleware
app.use(cors());
app.use(bodyParser.json());

var tasks = [];

// This will serve the HTML page todo.html
app.get('/', function(req, res) {
  res.sendFile('todo.html', {
    root: __dirname
  });
});

// GET all tasks
app.get('/tasks', function(req, res) {
  res.set('Content-Type', 'application/json')
  res.status(200).send(tasks);
});

// POST to add a task
app.post('/task', function(req, res) {
  res.set('Content-Type', 'application/json')

  /* HELP ME HERE */

  // returns 201 on success
  res.status(201);
});

// DELETE a task
app.delete('/task', function(req, res) {

  /* HELP ME HERE */

  // returns 204 on success
  res.status(204);
});

// DELETE all tasks
app.delete('/tasks', function(req, res) {

  /* HELP ME HERE */

  // returns 204 on success
  res.status(204);
});

//

// Listen for HTTP requests on port 3000
app.listen(3000, function() {
  console.log("listening on port 3000");
});

我想通过“TODO”和“COMPLETED”将文本框值传递给 JSON 过滤器。
如果我添加一个新的 TODO 列表,它会转到 JSON,如果值转到 COMPLETED,它也会转到 JSON

这是我想要的示例 JSON 结果:

{"TODO" : [ "Go to market", "Eat dinner with Daniel"], "COMPLETED" : [ "Wash dishes", "Go to gym and Workout" ]}


这只是一个示例,因此你们可以更改格式。
请随时向我提供所有欢迎的反馈。顺便说一句,我刚开始学习如何编码
感谢您花时间在这上面,即使您没有帮助我,祝您有美好的一天!

【问题讨论】:

  • 您的“示例 JSON”不是正确的 JSON。
  • 你采样 JSON--- {"TODO" : [ "去市场", "和 Daniel 一起吃晚餐"], "COMPLETED" : [ "洗碗", "去健身房锻炼" ]}

标签: javascript jquery node.js json express


【解决方案1】:

您所要做的只是对 Nodejs API 进行 Ajax 调用。例如,'/task' 并将输入字段值作为 json 格式的参数传递,然后只需在 Nodejs 中以 req.params.yourjsonKeys 的形式获取它们。

var inputData = $("#items").val();

$.ajax({
  url: "/tasks",
  type: "POST",
  data: {params: inputData},
  dataType: "html",
  success: function(data){
     if(data.code === 200){ // the response key 'code' from Nodejs
        alert('Success');
     }
  }
});

接下来,一旦你有了参数,你所要做的就是使用file system将它写入你的文件,如下所示:

创建一个包含表格数组的javascript对象

var obj = {
   table: []
};

向它添加一些数据,例如

obj.table.push({id: req.params.id , square: req.params.square});

使用 stringify 将其从对象转换为字符串

var json = JSON.stringify(obj);
//use fs to write the file to disk

var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);

如果你想追加它,请读取 json 文件并将其转换回对象

fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
}});

完整代码:

// POST to add a task
app.post('/task', function(req, res) {
  res.set('Content-Type', 'application/json')
    var obj = {
       table: []
    };

    obj.table.push({id: req.params.id , square: req.params.square});
    
    var json = JSON.stringify(obj);

    var fs = require('fs');

    fs.writeFile('myjsonfile.json', json, 'utf8', callback)

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {

        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 

        // returns 201 on success
        res.json({
           code: 201,
           message: 'Success'
        });

    }});

});

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多