javascript websocket onmessage event.data

Using JavaScript WebSocket how to pass event.data out onMessage function?

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.

I tried

function wcConnection (){
   this.dataInput = '';
}

Inside onMessage function, I added

function onMessage (evt)
{
   alert (evt.data);
   this.dataInput = evt.data;
}

Any help would be appreciated.


If you server is python tornado

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


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 = function(evt) { responseData(evt); };
function responseData(evt) {
    /* Here is your data, Do you what you want! */
    console.log(JSON.parse(evt.data));
}
链接地址: http://www.djcxy.com/p/70202.html

上一篇: 与交互的字符串

下一篇: javascript websocket onmessage event.data