我有一个按钮,当按下该按钮时,我希望它将对象数组(日志)从该js文件发送到节点js文件,以便随后输出JSON文件。我已经用this tutorial and this one尝试了AJAX,但是我仍然不明白如何在js和node之间传递变量。
const done_but = document.getElementById("done");
var logs = []
var xhttp = new XMLHttpRequest();
document.getElementById('r2').checked = true;
done_but.onclick = function() {
const student = document.getElementById("student-drop").value;
const face = document.querySelector('input[name="faceses"]:checked').value;
const time = new Date();
logs.push([{
student: student,
face: face,
time: time.toUTCString()
}]);
xhttp.open("POST", "file:///(file path)/index.html");
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhttp.send(logs);
console.log(logs);
};
答案 0 :(得分:0)
我发现,如果您将样式和本地js放入HTML文件,则可以将其写入屏幕,然后从本地js获取任何输入。要提供服务器数据,您可以
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8000");
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhttp.send(YourVar);
这是我的节点代码,用于输入并编写屏幕。
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(data);
res.end();
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
console.log(body);
console.log("");
res.end('ok');
});
}
});
}).listen(8000);
有用的链接:How to send JSON data How to send data Handling requests