【发布时间】:2016-11-04 07:21:41
【问题描述】:
我一直在学习使用 socket 的 express,但我似乎无法让我的代码按照我想要的方式工作。基本上我正在做一个 $.get 调用,它通过并替换我的索引页面上的 HTML。这是在服务器确认添加的新用户满足正确要求后完成的。
$.get 完美运行,它通过其他文件 html 提取。然而,套接字事件随后停止工作,我不明白为什么。它应该做的是在聊天框旁边添加个人用户名,当有人输入内容时,它也应该反映这一点。
似乎服务器不喜欢我调用不同的文件或类似的东西?
这是我的 GIT 的直接链接:https://github.com/factordog/letsGuess 因此,如果您需要查看所有设置的方式可以直接检查,我不确定需要什么。
这是有问题的代码:
$.get("./pages/game.html" ,function(data){
console.log(data);
$("#test").html(data);
});
这是真正的客户端 js:
$(function($) {
// Variables
var socket = io.connect(),// Creates the connection variable
setUsername = $("#setUsername"), //Form for when a user join
newUser = $("#username"), // Input for where user inputs a name
userSuccess = $(".successMessage"), // Success container for valid username
userError = $(".errorMessage"), // Error container for invalid username
playerOne = null,
playerTwo = null;
// Submit function for when a user submits their desired username
setUsername.submit(function(e){
// Prevent sumbit button default
e.preventDefault();
// Gets value of the username. function(data) allows us to reference the app.js
// data which is the array of new users.
socket.emit("new user", newUser.val(), function(data){
// Checks if name is valid else displays an error
if(data) {
socket.on("full_lobby_check", function(data){
console.log(data.lobbyStatus);
});
// Fades out the login page
userSuccess.removeClass("hide");
setTimeout(function(){
$("#loginPage").fadeOut();
}, 1000);
// Create a smoother transition between pages
$.get("./pages/game.html" ,function(data){
console.log(data);
$("#test").html(data);
});
setTimeout(function(){
$('#gamePage').fadeIn();
}, 2000);
} else {
userError.removeClass("hide");
}
});
newUser.val("");
});
// ===============================================
// PLAYER VS PLAYER APPEND
// ===============================================
// Append player names to battle
socket.on("event_new_user", function(data){
playerOne = data.userOne;
playerTwo = data.userTwo;
$(".playerOne").append(playerOne);
$(".playerTwo").append(playerTwo);
});
// ===============================================
// MESSAGE BOX LOGIC
// ===============================================
var users = $(".playersOnline"), // Area to append all users names
messageForm = $(".sendMessage"),
messageBox = $(".message"),
chat = $(".chat");
// Display all the usernames in chat room area
socket.on("usernames", function(data){
var html ="";
for(i=0 ; i < data.length; i++) {
html += data[i] + "<br/>";
}
users.html(html);
});
// On sumbit sends message to server to be fufilled
messageForm.click(function(e){
// Prevent sumbit button default
e.preventDefault();
socket.emit("send message", messageBox.val());
messageBox.val('');
});
// Appends the new message from the user to the chat box
socket.on("new message", function(data){
console.log(data.user);
chat.append("<b>" + data.user + ": </b>" + data.msg + "<br/>");
});
})
;
编辑:
包含当前的pastebin:http://pastebin.com/WUzwuPrf
【问题讨论】:
标签: javascript html node.js socket.io