javascript websocket onmessage event.data
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15514155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript websocket onmessage event.data
提问by user33054
Using JavaScript WebSocket how to pass event.data
out onMessage
function?
使用JavaScript的WebSocket怎么传event.data
出来onMessage
的功能?
var eventData = EventRequest("text");
..... codes .....
EventRequest = function (text)
{
var socket = new WebSocket ('ws://localhost:8080/');
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
function onOpen (evt)
{
socket.send("text");
}
function onMessage (evt)
{
alert (evt.data);
return evt.data;
}
};
I tried different ways to pass evt.data out, but I have not been able to. I can see the correct evt.data
data. I just can not pass the data out of onMessage
function.
我尝试了不同的方法来传递 evt.data,但我一直没能做到。我可以看到正确的evt.data
数据。我只是无法将数据传递出去onMessage
。
I tried
我试过
function wcConnection (){
this.dataInput = '';
}
Inside onMessage
function, I added
在onMessage
函数内部,我添加了
function onMessage (evt)
{
alert (evt.data);
this.dataInput = evt.data;
}
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Terry
If you server is python tornado
如果你的服务器是 python 龙卷风
def on_message(self, message):
t = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
self.write_message(t)
In your client, to retrieve the message, you could do
在您的客户端中,要检索消息,您可以执行以下操作
ws.onmessage = function (evt) {
console.log(JSON.parse(event.data));
}
you should see the json in the console
您应该会在控制台中看到 json
回答by Mohit Satish Pawar
Why are you returning value to websocket.onmessage function? This is the function where you got that value. If you want to pass the value to another function just pass the event object to that function and access it using "evt.data".
为什么要向 websocket.onmessage 函数返回值?这是您获得该值的函数。如果您想将值传递给另一个函数,只需将事件对象传递给该函数并使用“evt.data”访问它。
websocket.onmessage = function(evt) { responseData(evt); };
function responseData(evt) {
/* Here is your data, Do you what you want! */
console.log(JSON.parse(evt.data));
}