JSON.parse(e.data) - websocket's onmessage - 引用错误:e 未定义/未定义的"数据"/WebSocket 已处于关闭或关闭状态



websocket/JSON 新手在这里。我在从函数事件接收数据时遇到问题。有人可以帮助我吗?

看起来消息已正确发送到服务器(使用 sendMessage(( 函数时message_cart值正确(,但在接收数据时出现问题。

我的控制台:

websocket.min.js:35 未捕获的类型错误:无法读取属性"数据" 定义 at receiveMessage (websocket.min.js:35(

从购物车到服务器的消息:10//数字正确

websocket.min.js:83 WebSocket 已处于 CLOSED 或 CLOSED 状态。

我的网络.js:

document.addEventListener('DOMContentLoaded', function(){
'use strict';
var ws_protocol = 'ws://';
if (window.location.protocol == "https:")
ws_protocol = 'wss://';
var ws_url = ws_protocol + window.location.host + '/ws/auctions/' + qs;
var webSocket = new WebSocket(ws_url);
var amountbutton = document.getElementsByClassName('amountButton');
var message_cart;
webSocket.onopen = sendMessage();
webSocket.onmessage = receiveMessage();
function receiveMessage(e) {
var msgData = JSON.parse(e.data);
if ('auction_data' in msgData) {
console.log("here we are, 'auction_data' in msgData");
} else if ('cart_data' in msgData) {
console.log("here we are, 'cart_data' in msgData");
}
};
function sendMessage() {
for(let i = 0; i < amountbutton.length; i++) {
amountbutton[i].onclick = (e) => {
if(!amountbutton[i].nextElementSibling) {
message_cart = amountbutton[i].previousElementSibling.value;
message_cart++;
} else {
message_cart = amountbutton[i].nextElementSibling.value;
message_cart--;
}
console.log("message from cart to server: " + message_cart);
webSocket.send(message_cart);
}
}
}
webSocket.onclose = function(e) {
console.error('Websocket closed.');
};
}, false);

为了让 Web 套接字调用您的onopenonmessage回调,您必须将它们作为函数分配给侦听器,而不是作为这些函数返回的值。因此,解决方案是只分配这些函数而不调用它们,如下所示:

webSocket.onopen = sendMessage; // <- no curly braces in there
webSocket.onmessage = receiveMessage; // <- no curly braces in there

希望对:)有所帮助

相关内容

  • 没有找到相关文章