【发布时间】:2017-11-27 14:59:56
【问题描述】:
我通过运行 Ajax 调用来增加服务器上的值,并希望在执行此操作后更新我的 UI
function increaseHitpoints(){
$.ajax({
type: 'GET',
url: 'http://localhost:8888/incHp/2312'
}).done(function (data) {
$("#txtHitpoints").html(data);
});
}
在我的 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 <-
});
});
});
如果我想返回新值,我必须将什么传递给缺失的部分?新值将是 hitpoints
我试过res.send(hitpoints);,但似乎这个函数想要返回一个状态码,而不是一个值。
【问题讨论】:
标签: javascript jquery node.js ajax express