我的client.html文件中有此表单
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<link rel="stylesheet" type="text/css" href="/css/client.css">
</head>
<body>
<div class="wrapper">
<div class="chatBox">
<div class="chatBoxHead">Chat with Support</div>
<div class="contentArea" style="display: none">
<div class="formArea">
<div class="title">Please fill out this form</div>
<form class="loginForm" id="loginForm">
<div class="inputContainer">
<label for="name"></label>
<input class="nameInput" type="text" placeholder=" * Name" name="name" id="name" required />
</div>
<div class="inputContainer">
<label for="email"></label>
<input class="emailInput" name="email" id="email" type="email" placeholder=" * Email" required />
</div>
<button class="submit" >Submit</button>
</form>
</div>
<div class="chatArea" style="display: none">
<div class="messages">
<div class="oldMsg"></div>
<div class="newMsg"></div>
</div>
<div class='typing'></div>
<input class="inputMessage" rows="1" placeholder="Type here..."></input>
</div>
</div>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="../js/client.js"></script>
</body>
</html>
当我点击登录表单的提交按钮时,它会将数据保存到数据库,然后重新加载,而不是保存数据,然后显示聊天区域以进行消息传递。这是我的client.js文件
var $window = $(window);
var socket = io();
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $nameInput = $('.nameInput');
var $emailInput = $('.emailInput');
var $formArea = $('.formArea');
var $contentArea = $('.contentArea');
var $login = $('#loginForm');
var $chatArea = $('.chatArea');
var $typing = $(".typing");
var $oldMsg = $('.oldMsg');
var $newMsg = $('.newMsg');
var typing = false;
var timeout = undefined;
var id = localStorage.getItem("roomID");
var active = sessionStorage.getItem('active');
if (active && id) {
$formArea.hide();
$chatArea.show();
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$contentArea.show();
}
$('.chatBoxHead').click(function() {
$contentArea.slideToggle('slow');
if (id != null && !active) {
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$formArea.hide();
$chatArea.show();
$inputMessage.focus();
sessionStorage.setItem('active', true);
active = true;
}
});
$login.submit(function() {
$chatArea.show();
$formArea.hide();
$inputMessage.focus();
sessionStorage.setItem('active', true);
socket.emit('add user', {
isNewUser: true,
Name: $nameInput.val().trim(),
Email: $emailInput.val().trim()
});
});
$inputMessage.keypress(function(event) {
if (event.which !== 13) {
if (typing === false && $inputMessage.is(":focus")) {
typing = true;
socket.emit("typing", {
isTyping: true,
roomID: id,
person: "Client"
});
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 2000);
}
} else {
sendMessage();
clearTimeout(timeout);
timeoutFunction();
}
})
socket.on('chat message', function(data) {
var sender;
if (data.isAdmin){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data.message + '<span class="timestamp">' +
((data.timestamp).toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
function sendMessage() {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
var encodedMessage = $('<div />').text(message).html();
message = encodedMessage;
if (message) {
$inputMessage.val('');
var time = ("" + new Date().getTime());
socket.emit('chat message', {
roomID: "null",
message: message,
timestamp: time
});
var $messageBodyDiv = $('<div class="msg_client">' + message + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
function timeoutFunction() {
typing = false;
socket.emit("typing", {
isTyping: false,
roomID: id,
person: "Client"
});
}
$messages.on("scroll", function() {
if ($messages.scrollTop() == 0)
socket.emit("more messages", {});
})
socket.on('roomID', function(roomID) {
id = roomID;
localStorage.setItem("roomID", roomID);
});
socket.on('typing', function(data) {
if (data.isTyping && data.person != 'Client')
$Typing.append("Support is typing...");
else
$Typing.text('');
});
socket.on('chat history', function(data) {
var len = data.history.length;
for (var i = len - 1; i >= 0; i--)
addMessages(data.history[i], false);
});
socket.on('more chat history', function(data) {
var len = data.history.length;
for (var i = 0; i < len; i++)
addMessages(data.history[i], true);
});
function addMessages(data, getMore) {
var sender;
if (data["who"]){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data["message"] + '<span class="timestamp">' +
(data["timeStamp"]).toLocaleString().substr(15, 6) + '</span></div>');
if (getMore) {
$messageBodyDiv.insertAfter($oldMsg);
$messages[0].scrollTop += $messageBodyDiv.outerHeight();
} else {
$messageBodyDiv.insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
socket.on('log message', function(text) {
var time = ("" + new Date().getTime());
var $messageDiv = $('<div class="msg_admin">' + text + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
socket.on('disconnect', function() {
console.log("Disconnected!");
$inputMessage.prop('disabled', true);
$inputMessage.prop('placeholder', "Connection Lost! Reconnecting..");
});
socket.on('reconnect_failed', function() {
console.log("Reconnection Failed!");
$inputMessage.prop('placeholder', "No active connection. Please refresh page.");
});
socket.on('reconnect', function() {
setTimeout(function() {
console.log("Reconnected!");
$inputMessage.prop('disabled', false);
$inputMessage.prop('placeholder', "Type here...");
if (active && id)
socket.emit('add user', {
isNewUser: false,
roomID: id
});
}, 10000);
});
此处还有我的app.js文件
var express = require('express');
var app = express();
var fs = require('fs');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var uuid = require('uuid');
var config = require(__dirname + "/config.js");
var r = require('rethinkdb');
var _ = require("underscore");
var db = require('./controllers/db');
var btoa = require('btoa');
var users = {};
var admins = {};
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(require("express-session")({
secret: "luxtag chat",
resave: false,
saveUninitialized: false
}));
// Setup rethinkDB database
db.setupDB();
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/client.html');
});
app.get(config.rethinkdb.admin_url, function(req, res) {
res.sendFile(__dirname + '/views/admin.html');
});
io.on('connection', function(socket){
console.log(`Socket ID: ${socket.id}`);
console.dir(socket.handshake, {colors: true});
//Admin login
socket.on('login', function(data) {
if (btoa(data.password) != config.rethinkdb.key)
socket.emit('login', {
login: false,
err: "Invalid Login"
})
else {
if (_.find(config.rethinkdb.admin_users, function(admin) {
return (admin == data.admin);
})) {
if (admins[data.admin]) {
socket.emit('login', {
login: false,
err: "Already Logged In"
})
} else {
socket.emit('login', {
login: true
})
}
} else {
socket.emit('login', {
login: false,
err: "Invalid Login"
})
}
}
});
socket.on('add admin', function(data) {
this.isAdmin = data.isAdmin;
socket.username = data.admin;
console.log('admins: ', admins);
console.log('users: ', users);
_.each(admins, function(adminSocket) {
adminSocket.emit("admin added", socket.username)
socket.emit("admin added", adminSocket.username)
});
admins[socket.username] = socket;
//If some user is already online on chat
if (Object.keys(users).length > 0) {
_.each(users, function(userSocket) {
db.getMessages(userSocket.roomID, 0)
.then(function(history) {
var len = history.length;
var userSocket = users[history[len - 1]];
history.splice(-1, 1);
socket.join(userSocket.roomID);
socket.emit("New Client", {
roomID: userSocket.roomID,
history: history,
details: userSocket.userDetails,
justJoined: true
})
})
});
}
});
socket.on('add user', function(data) {
socket.isAdmin = false;
if (data.isNewUser) {
data.roomID = uuid.v4();
var user = {
id: data.roomID,
name: data.Name,
email: data.Email
}
console.log(user);
db.saveUser(user, function (saved, err) {
if (saved) {
console.log('user saved...');
return;
}
if (err) {
console.log('There was an error creating the account');
}
else {
console.log("The account wasn't created");
}
});
socket.emit("roomID", data.roomID);
}
socket.roomID = data.roomID;
console.log('socket.roomID: ', socket.roomID);
//get user
db.findUserById(socket.roomID, function(err, details) {
if(err){
console.log("Line 60 : ", error);
}
else {
socket.userDetails = details;
console.log('socket.userDetails: ', socket.userDetails);
}
});
socket.join(socket.roomID);
var newUser = false;
if (!users[socket.roomID]) {
users[socket.roomID] = socket;
newUser = true;
}
//get message history
db.getMessages(socket.roomID, 0)
.then(function(history) {
history.splice(-1, 1)
socket.emit('chat history', {
history: history,
getMore: false
});
if (Object.keys(admins).length == 0) {
//Tell user he will be contacted asap
socket.emit('log message', "Thank you for reaching us." +
" Please leave your message here and we will get back to you shortly.");
} else {
if (newUser) {
socket.emit('log message', "Hello " + socket.userDetails['name'] + ", How can I help you?");
//Make all available admins join this users room.
_.each(admins, function(adminSocket) {
adminSocket.join(socket.roomID);
adminSocket.emit("New Client", {
roomID: socket.roomID,
history: history,
details: socket.userDetails,
justJoined: false
})
});
}
}
})
.catch(function(error) {
console.log("Line 113 : ", error)
})
.done();
db.getMsgLength(socket.roomID)
.then(function(len) {
socket.MsgHistoryLen = (len * -1) + 10;
socket.TotalMsgLen = (len * -1);
})
.catch(function(error) {
console.log("Line 121 : ", error)
})
.done();
});
socket.on('chat message', function(data){
if (data.roomID === "null"){
data.roomID = socket.roomID;
}
data.isAdmin = socket.isAdmin;
var msg = {
who: data.isAdmin,
message: data.message,
timestamp: data.timestamp
}
db.saveMessage(msg, function (err, saved) {
if (err || !saved) {
console.log('There was an error saving your message');
return;
}
socket.broadcast.to(data.roomID).emit('chat message', data);
});
});
socket.on("typing", function(data) {
socket.broadcast.to(data.roomID).emit("typing", {
isTyping: data.isTyping,
person: data.person,
roomID: data.roomID
});
});
socket.on("more messages", function() {
if (socket.MsgHistoryLen < 0) {
db.getMessages(socket.roomID, socket.MsgHistoryLen)
.then(function(history) {
history.splice(-1, 1)
socket.emit('more chat history', {
history: history
});
})
socket.MsgHistoryLen += 10;
}
});
socket.on('disconnect', function() {
if (socket.isAdmin) {
delete admins[socket.username];
_.each(admins, function(adminSocket) {
adminSocket.emit("admin removed", socket.username)
});
} else {
if (io.sockets.adapter.rooms[socket.roomID]) {
var total = io.sockets.adapter.rooms[socket.roomID]["length"];
var totAdmins = Object.keys(admins).length;
var clients = total - totAdmins;
if (clients == 0) {
//check if user reconnects in 10 seconds
setTimeout(function() {
if (io.sockets.adapter.rooms[socket.roomID]){
total = io.sockets.adapter.rooms[socket.roomID]["length"];
}
totAdmins = Object.keys(admins).length;
if (total <= totAdmins) {
delete users[socket.roomID];
socket.broadcast.to(socket.roomID).emit("User Disconnected", socket.roomID);
_.each(admins, function(adminSocket) {
adminSocket.leave(socket.roomID)
});
}
}, 10000);
}
} else {
if (socket.userDetails)
delete users[socket.roomID];
}
}
});
});
http.listen(config.express.port, function(){
console.log('listening on *:' + config.express.port);
});
非常感谢任何帮助。
答案 0 :(得分:0)
在js
中设置提交功能,向服务器发出POST
请求并阻止默认行为。 jQuery
示例:
$( "#target" ).submit(function( event ) {
event.preventDefault();
// Do post request here
});
答案 1 :(得分:0)
我想,在数据存储在数据库中之后,你得到success promise
。
您需要阻止自动表单提交。请看下面的代码。
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return toSubmit();">
First name:<br>
<input id="name" type="text" name="firstname" >
<br>
Last name:<br>
<input type="text" name="lastname" >
<br><br>
<button type="submit" >Submit</button>
</form>
<script>
function toSubmit(){
if(document.getElementById('name').value == "tushar"){
alert("success");
return true;
}
else{
alert("failed");
return false;
}
}
</script>
</body>
</html>