1 回答
TA贡献1966条经验 获得超4个赞
服务器端:
io.on('connection', (socket) => {
console.log('socket connect successful');
socket.on('new_message', function(message) {
console.log('Client says', message);
io.emit('new_message', message)
})
})
app.get("/get_messages", function(request, result) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results) {
result.end(JSON.stringify(results));
});
});
客户端
function loadcomments() {
fetch('http://localhost:5502' + '/get_messages')
.then(response => {
if (response.ok) {
console.log('success')
console.log(response);
} else {
console.log('failure')
}
return response.json();
})
.then(function(data) {
io.emit("new_message", data)
io.on("new_message", function(data) {
console.log("Server says", data);
output.innerHTML = '';
data.forEach(function(user) {
var newUser = document.createElement("div");
var newName = document.createElement("h5");
var newDate = document.createElement("h5");
var newMessage = document.createElement("h6");
var display_username = document.createTextNode(JSON.stringify(user.username));
var display_date = document.createTextNode(JSON.stringify(user.date));
var display_comments = document.createTextNode(JSON.stringify(user.comments));
newName.appendChild(display_username);
newDate.appendChild(display_date);
newMessage.appendChild(display_comments);
newUser.appendChild(newName);
newUser.appendChild(newDate);
newUser.appendChild(newMessage);
output.appendChild(newUser);
请注意我如何构建这部分:
.then(function(data) {
io.emit("new_message", data)
io.on("new_message", function(data) {
console.log("Server says", data);
output.innerHTML = '';
data.forEach(function(user) {
var newUser = document.createElement("div");
我遇到的问题是我一直在数据库中获取第一个条目作为输出并重复。放置这个
io.emit("new_message", data);
io.on("new_message", function(data) {
在此之上:
output.innerHTML = '';
data.forEach(function(user) {
解决了问题。
添加回答
举报