【发布时间】:2015-12-23 16:28:45
【问题描述】:
我正在构建一个聊天应用程序,我想要求用户输入他们的用户名。 JQuery 前端代码将表单滑入视图(准备就绪),将数据存储到变量中,然后加载聊天(当按下回车键或按钮时)。在验证服务器端的用户输入之前,如何停止该动画?我正在使用 node.js 作为后端。有什么想法吗?
提前致谢!
前端 jQuery:
var nameChoice, roomChoice; //to store user input
var initName = function() {
nameChoice = $("#init-name input").val(); //save chosen name in nameChoice
$("#current-name").text("Username: " + nameChoice); //put chosen name in chat header
$("#init-name").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#init-room").removeClass("hidden");
$("#init-room").animate({"left" : "35%"}, 300);
}); //remove name form and slide in room form in callback
} //end initName
var initRoom = function() {
roomChoice = $("#init-room select").val(); //save chosen room in roomChoice
$("#current-room").text("Room: " + roomChoice); //put chosen room in chat header
$("#init-room").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#chat-main").removeClass("hidden");
}); //remove room form and show page in callback
} //end initRoom
var btnHover = function() {
$(".btn-form").hover(
function() {
$(this).stop().animate(
{
backgroundColor : "#FFBD7A"
}, 300);
},
function() {
$(this).stop().animate(
{
backgroundColor : "white"
}, 300);
});
}
var init = function() {
$("#init-name").removeClass("hidden").animate({"left" : "35%"}, 300); //slide in name form
$(document).keydown(function(event) { //submit choice on enter key
if (event.which === 13) {
if (!$("#init-name").hasClass("hidden")) { //if user is choosing name
event.preventDefault();
initName(); //call initName function
}
if (!$("#init-room").hasClass("hidden")) { //if user is choosing room
event.preventDefault();
initRoom(); //call initRoom function
}
}
}); //end enter key submission
$("#init-name .btn-form").click(initName);
$("#init-room .btn-form").click(initRoom);
btnHover();
} //end init
$(document).ready(init);
我还在学习node,所以还没有后端代码...
【问题讨论】:
-
请贴一些代码。
-
但是从一般意义上回答你的问题,当用户按下回车键时,将数据发送到后端(AJAX)并让它返回成功或失败的响应,然后继续如果成功返回,则加载聊天,否则将用户留在表单上。
-
好的,现在,将用户名发送到服务器的调用在哪里?
-
它可以在另一个文件中,但此代码需要调用后端要求它验证用户,您可以使用 jQuery Ajax 实现这一点。如果没有后端,那么你就没有真正的聊天应用程序,你只有一个看起来应该存在聊天的页面;因为您需要以某种方式验证用户。
-
我推荐看看这些:github.com/IgorAntun/node-chat,github.com/tamaspiros/advanced-chat,和socket.io/get-started/chat,你可以看到他们是如何实现聊天的。这真的不是你的问题,而是下一步。
标签: javascript jquery node.js frontend backend