【发布时间】:2020-05-30 22:30:41
【问题描述】:
websocket/JSON 新手在这里。我从函数事件接收数据时遇到问题。有人可以帮我吗?
看起来消息已正确发送到服务器(使用 sendMessage() 函数时正确的 message_cart 值),但在接收数据时出现问题。
我的控制台:
websocket.min.js:35 Uncaught TypeError: Cannot read property 'data' of 不明确的 在receiveMessage (websocket.min.js:35)
从购物车到服务器的消息:10 // 数字正确
websocket.min.js:83 WebSocket 已经处于 CLOSING 或 CLOSED 状态。
我的 websocket.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);
【问题讨论】:
标签: javascript json websocket