简体   繁体   English

使用Ajax调用将数据从NodeJS发送到客户端

[英]Sending data from NodeJS to the client by using Ajax calls

I increase a value at the server by running an Ajax call and want to update my UI after doing this 我通过运行Ajax调用在服务器上增加了价值,并想在执行此操作后更新我的UI

function increaseHitpoints(){
  $.ajax({
    type: 'GET',
    url: 'http://localhost:8888/incHp/2312'
  }).done(function (data) {
    $("#txtHitpoints").html(data);
  });
}

In my app.js I read a JSON file, manipulate the value, write it back to the file and return it to the client 在我的app.js中,我读取了一个JSON文件,操纵该值,将其写回到文件中,然后将其返回给客户端。

app.get('/incHp/:id', function (req, res) {
  var database = './database.json';
  fs.readFile(database, 'utf8', function (err, data) { // read the data
      var json = JSON.parse(data);
      var users = json.users;
      var hitpoints;
      users.find(u => {
          if (u.id === Number(req.params.id)) { // get the user by id
            u.hitpoints++;
            hitpoints = u.hitpoints;
          }
      });
      json = JSON.stringify(json);
      fs.writeFile(database, json, (err) => { // update the JSON file

           // -> missing part here <-

      });
  });
});

what do I have to pass into the missing part if I want to return the new value? 如果我想返回新值,我该如何传递缺失部分? The new value would be hitpoints 新的价值就是hitpoints

I tried res.send(hitpoints); 我尝试过res.send(hitpoints); but it seems this function wants to return a status code, not a value. 但似乎此函数要返回状态码,而不是值。

If you send a numerical value, it will be observed as an HTTP response code https://expressjs.com/en/api.html#res 如果您发送数值,它将被视为HTTP响应代码https://expressjs.com/en/api.html#res

But you can send your hitpoints as a string res.send(hitpoints.toString()) or as json res.send({hits: hitpoints}); 但是您可以将res.send({hits: hitpoints});作为字符串res.send(hitpoints.toString())或json res.send({hits: hitpoints});

Depends on what format you want your response to be. 取决于您希望回复的格式。 I prefer using JSON. 我更喜欢使用JSON。 So in JSON case you would do this: 因此,在JSON情况下,您可以这样做:

fs.writeFile(database, json, (err) => { 
  res.status(200).json({yourKey: yourValue});
});

Then you can access the JSON object in your frontend: 然后,您可以在前端访问JSON对象:

$("#txtHitpoints").html(data.yourKey);

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

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