使用JQuery更新JSON文件以执行AJAX调用nodejs

时间:2016-06-22 21:03:36

标签: jquery json ajax node.js

我想通过在表单中​​使用用户输入将新用户添加到json文件 我可以使用下面的代码将信息上传到txt文件,但我不知道如何使用json,任何帮助,谢谢你

ejs文件:

<!DOCTYPE html>
<html>
<head>
<title> users </title>
</head>

<body>
  <h1>Users</h1>
  <% include templates/header.ejs %>

  <form action="http://127.0.0.1:3000/users" id="new" method="post" enctype='application/json'>
    <div id="form">
      <label for="lname">Last Name</label> <input type="text"  id="lname" name="lname">

      <label for="fname">First Name</label><input type="text"id="fname"name="fname">

      <label for="id">ID</label><input type="text"id="id"name="id">

      <button type="submit" id= "submit" value="Submit" >Submit</button>

 </form>

</body>
</html>

user.js文件:

var express = require('express');
var router = express.Router();
var fs = require("fs");

router.get('/', function(req, res, next) {
  res.render('users');
});


//will send the user input
router.post('/', function(req, res) {

  var first= req.body.fname;
  var last= req.body.lname;
  var id= req.body.id;

  filePath = __dirname + '/people.txt';
  fs.appendFile(filePath, JSON.stringify(first + "   " + last + "   "+ id ),   function () {
    res.end();
  });

});

router.get('/listUsers', function (req, res) {
  fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {

    console.log( data );
    res.end( data );
  });
})

module.exports = router;

1 个答案:

答案 0 :(得分:1)

我建议不要使用文件来执行此操作。但是,如果您坚持,则可以始终以标准JSON格式保存数据。为此,您可以执行以下操作:

var express = require('express');
var router = express.Router();
var fs = require("fs");

router.get('/', function(req, res, next) {
res.render('users');
});


 //will send the user input
 router.post('/', function(req, res) {

  var first= req.body.fname;
  var last= req.body.lname;
  var id= req.body.id;

   var person = {
     first: first,
     last: last,
     id: id
   }; // if you are using es6 you do var person = {first, last, id}

  var filePath = __dirname + '/people.json';
  fs.readFile(filePath, function (err, file) {
    if (err) {
      res.status = 500;
      res.send(err).end();
      return;
    }

    var fileString = file.toString();
    var people = fileString ? JSON.parse(fileString) : [];
    people.push(person);
    fs.writeFile(filePath, JSON.stringify(people), function(err) {
       if (err) {
        res.status = 500;
        res.send(err).end();
        return;
      }

      res.end();
    });
  });
});



router.get('/listUsers', function (req, res) {
  fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
    if (err) {
      res.status = 500;
      res.send(err).end();
      return;
    }
    res.json(JSON.parse(data));
  });
})



module.exports = router;