WebSocket 在代码中返回 undefined 但不在控制台中 [英] WebSocket returns undefined in code but not in console
问题描述
我正在努力理解这里发生了什么......
I'm struggling to understand what's happening here...
我在 192.168.1.64:81 上有一个 websocket 服务器
I have a websocket server on 192.168.1.64:81
我需要使用此 javascript 将数据从网页发送到套接字:
I need to send data to the socket from a web page using this javascript:
window.onload = function() {
var connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
connection.onopen = function() {
connection.send('Connect ' + new Date());
};
connection.onerror = function(error) {
console.log('WebSocket Error ', error);
};
connection.onmessage = function(e) {
console.log('Server: ', e.data);
};
function sendData() {
var data="#"+joystick.deltaX()+","+joystick.deltaY();
connection.send(data);
}};
现在是这样的:如果我打开 js 控制台(在 firefox 中),我会看到连接未定义"错误......但是如果我将行复制粘贴到控制台:
Now this is what happens: if I open the js console (in firefox) I see the "connection is undefined" error... but if I copy-paste to the console the line:
var connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
socket 被正确定义,更新程序开始通过 socket 正确传输数据!!
the socket gets defined correctly and the updater begins streaming data correctly through the socket!!
我错过了什么?我应该知道一些众所周知的问题吗?
What am I missing? Should I be aware of some well known issue?
推荐答案
以下函数使用了 connection
变量,但是变量超出了作用域,因为 connection
是使用 var
(本地)关键字定义:
The following functions use the connection
variable, but the variable is out of scope, because connection
is defined using the var
(local) keyword:
connection.onopen = function() {
connection.send('Connect ' + new Date());
};
function sendData() {
var data="#"+joystick.deltaX()+","+joystick.deltaY();
connection.send(data);
}};
或者将`connection 定义为全局值:
Either define `connection as a global value:
connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
或者使用内部绑定/引用:
Or use an internal binding / reference:
connection.onopen = function(e) {
e.target.send('Connect ' + new Date());
};
sendData = function() {
var data="#"+joystick.deltaX()+","+joystick.deltaY();
this.send(data);
}.bind(connection);
否则将连接初始化为全局并像这样分配 onload:
Otherwise initialize connection as a global and assign onload like this:
var connection;
window.onload = function() {
connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
connection.onopen = function() {
connection.send('Connect ' + new Date());
};
connection.onerror = function(error) {
console.log('WebSocket Error ', error);
};
connection.onmessage = function(e) {
console.log('Server: ', e.data);
};};
这篇关于WebSocket 在代码中返回 undefined 但不在控制台中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!