<code
class
=
"html"
><!-- index.html -->
<script>
var
ws =
new
WebSocket(
"ws://localhost:8000/ws"
);
ws.onmessage =
function
(event) {
var
comments = document.getElementById(
'comments'
)
var
comment = document.createElement(
'li'
)
var
jsonObj = JSON.parse(event.data);
var
authorNode = document.createElement(
'h3'
);
authorNode.innerHTML = jsonObj.author;
var
contentNode = document.createElement(
'p'
);
contentNode.innerHTML = jsonObj.content;
comment.appendChild(authorNode);
comment.appendChild(contentNode);
comments.appendChild(comment)
};
function
addComment(event) {
var
author = document.getElementById(
"author"
)
var
content = document.getElementById(
"content"
)
ws.send(JSON.stringify({
"author"
: author.value,
"content"
: content.value
}))
author.value =
''
content.value =
''
event.preventDefault()
}
</script></code>