Socket.io官方聊天室DEMO的学习笔记

时间:2022-12-10 07:06:54

照着Socket.io官方的聊天室代码敲了一遍,遇到了一个奇怪的问题:

每次点击SEND按钮的时候,都会重新刷新页面。

在点击页面的一瞬间,
看到了正在加载jquery的提示,

然后以为是jquery用的官方cdn的问题导致的,

于是把从官方下载了一个jquery文件放到index.html同级目录,

结果在运行的时候死活找不到jquery文件,这个问题有待解决。

后面认认真真的思考了以下,

SEND按钮其实是没有点击事件的,按钮为啥会点击刷新页面了,

BING搜索了一下关键词:button+刷新页面,

发现果然是button的问题,

只要在button的属性里面加上type="button"那么就不会刷新了。

最终,能够正常跑起来的前端代码是这样子的:

 <!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<meta charset="UTF-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var socket = io(); $('form').submit(function(){
socket.emit('message',$('#m').val());
$('#m').val('');
return false;
});
function sendMsg(){
console.log('clicked');
socket.emit('message',$('#m').val());
$('#m').val('');
}
socket.on('connect',function(){
$('#messages').append($('<li>').text("Connected"));
socket.on('dmessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
}); </script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button type="button" id="sendbtn" onclick="sendMsg(event)" autopostback="false">Send</button>
</form>
</body>
</html>

index.html