app.js:
// 引入express模块 var express = require('express'); // 创建Web服务器对象 var app = express(); let chatMsgs = []; // 静态资源处理 app.use(express.static('public')); app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.listen(3000, () => console.log('服务器启动成功')); app.get('/getMsg', function (req, res) { res.send(chatMsgs); }); app.post('/sendMsg', function (req, res) { console.log(req.body); chatMsgs.push({ name: req.body.name, content: req.body.content }); }); app.post('/clearMsg', function (req, res) { console.log(req.body); if (req.body.cmd == 'clear') { chatMsgs = [];//清屏 } res.send('ok'); });
Ajax聊天室示例-后台清屏功能:clear.html:
Ajax聊天室示例-后台 清屏
前台聊天界面index.html:
Ajax聊天室示例 欢迎访问Ajax聊天室示例 发送 ' + new Date().toLocaleString() + " " + data[i].name + ':' + data[i].content + ''; // } // document.getElementById('chat').innerHTML = html; // } // } xhr.onload = function () { var data = JSON.parse(xhr.responseText); if (data.length !== tmpMsg.length) { tmpMsg = data; var html = ''; for (var i = 0; i ' + new Date().toLocaleString() + " " + data[i].name + '说:' + data[i].content + ''; } document.getElementById('chat').innerHTML = html; } } xhr.send(); //console.log('getMsg'); }, 1000); " _ue_custom_node_="true">
完整代码 chatroomEZ.7z