I'm using django-channels for implementing sockets in a django app.
I've followed instructions and it worked:
socket = new WebSocket("ws://127.0.0.1:8000/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send("hello world");
}
but when I use my own code:
<script type="text/javascript">
$(document).ready(function() {
socket = new WebSocket("ws://127.0.0.1:8000/chat/");
socket.onmessage = function (e) {
console.log(e.data);
};
$('form').submit(function () {
socket.send($('form>input[type="text"]').val());
});
});
</script>
My django server receives the message but socket.onmessage is not called. Where I'm going wrong?
adding the original code to the ready block is either not working?
socket.onopen = function() {
console.log("socket open")
socket.send("hello world");
}
It could be that the channel is not yet opened
That's code that worked
socket = new WebSocket("ws://127.0.0.1:8000/chat/");
socket.onmessage = function (e) {
alert(e.data);
};
$(document).ready(function () {
socket.onopen = function() {
$('button').click(function () {
socket.send($('#mes_input').val());
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.