html中有id是btn的按钮,然后绑定了事件:
document.querySelector("#btn").onclick = () => {
const msg = document.querySelector('#msg').value;
const post_time = new Date();
socket.emit('client_send', {
'name': '{{current_user.name}}',
'avatar': '{{current_user.get_gravatar_url()}}',
'msg': msg,
'time': post_time.toLocaleDateString()
});
// alert("send")
};
然后服务器收到消息,广播,接收服务器消息
@chat.route('/chatroom', methods=['POST', 'GET'])
def chatroom():
return render_template('/chatroom.html')
@socketio.on("client_send", namespace='/msg')
def client_send(data):
if data['msg'] != '':
emit('server_response',
{'name': data['name'],
'avatar': data['avatar'],
'msg': data['msg'],
'time': data['time'],
},
broadcast=True
)
log.debug(data)
message_box是显示消息的div
socket.on('server_response', function (res) {
// alert(res.msg)
var htmlData = '<div class="msg_item fn-clear">'
+ ' <div class="uface"><img src="' + res.avatar + '" width="40" height="40" alt=""/></div>'
+ ' <div class="item_right">'
+ ' <div class="msg own">' + res.msg + '</div>'
+ ' <div class="name_time">' + res.name + ' · ' + res.time + '</div>'
+ ' </div>'
+ '</div>';
$("#message_box").append(htmlData);
$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
});
但是每次emit之后页面都会自己刷新,一刷新,刚刚message_box里面append的内容就没了
怎么阻止它刷新呢?好像没查到什么相关资料