gpt4 book ai didi

javascript - Express中的Socket.io从客户端接收未定义的数据

转载 作者:行者123 更新时间:2023-12-03 03:46:25 26 4
gpt4 key购买 nike

我正在开发这个简单的井字棋应用程序,每当玩家点击按钮时,它就会触发函数 ma​​rkTheCell(button) 并传递按钮的 id。然后,该函数将玩家(字符串值)和按钮 id 发送到服务器。我将控制台日志放入客户端页面以查看是否传递了有效值,确实如此。但是当我尝试将其记录到服务器中时,播放器的值变成对象 Object 并且按钮 id 未定义。我不知道我是否未能正确放置和使用参数。希望有人提供帮助,因为我被困在这个问题上。

index.html

<body>
<div class="col-lg-4"></div>
<div class="col-lg-4 jumbotron">
<h4>You are player <span id="name"></span></h4>
<button id="one" onclick="markTheCell(this.id)" class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
</div>
<div class="col-lg-4"></div>
</div>

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var player = "";
$(document).ready(function () {

socket.on('player', function (playerNo) {
player = playerNo;
$('#name').text(playerNo);
});

socket.on('hitAMark', function (player, button) {
console.log("in client hit a mark player "+ player);
console.log("in client hit a mark button "+ button);
$(button).text(player);
});
})
function markTheCell(button) {
socket.emit('mark', {player,button });
console.log("in markTheCell client hit a mark player "+ player);
console.log("in markTheCell client hit a mark button "+ button);
}
</script>
</body>

index.js

var player = 0;
io.on('connection', function(socket){
if(player==0){
player++;
socket.emit('player', "X");
console.log("Player "+ player +" is connected");
}else if(player==1){
player++;
socket.emit('player', "O");
console.log("Player "+ player +" is connected");
}

socket.on('disconnect', function(){
console.log('A user is disconnected');
});


socket.on('mark', function(player, button){
console.log("in server hit a mark button "+ player);
console.log("in server hit a mark player "+button);

io.emit('hitAMark', {player,button});
});
});


http.listen(3000, function(){
console.log('Server is listening on port 3000!');
});

浏览器和cmd中控制台的截图: enter image description here

enter image description here

最佳答案

尝试发出{player:player,button:button}而不是{player,button}。也许它可以工作。

关于javascript - Express中的Socket.io从客户端接收未定义的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com