提交表单时重新加载网页 [英] Webpage reloading on submitting form
问题描述
我正在尝试使用Node.js和Socket.io创建一个Web聊天应用程序.我让用户在输入表单中键入内容,然后单击发送按钮以发送消息.现在它处于开发阶段,所以我只想看看消息是否从客户端传递到服务器.因此,在我的客户端上,当单击提交"按钮时,我使用了发出事件,并将消息传递给服务器.在服务器端,我有侦听此事件并将其注销的代码.但是,每次我运行它时,客户端都会在每次提交表单时断开并重新连接,并且消息没有按我的预期记录.
I'm trying to make a web chat application using Node.js and Socket.io. I have the user typing into a input form and then click a send button to send a message. Right now it's in a development stage, so I just want to see if the message gets passed from the client to the server or not. So on my client-side, when the submit button is clicked, I use emit an event, and pass a message to the server. On my server-side, I have code that listens for this event and logs it out. But every time I run it, the client disconnects and re-connects every time the form is submitted, and the message isn't getting logged as I expected.
这是来自app.js的代码
Here's the code from app.js
io.on('connection', function(socket){
console.log('Client connected!');
socket.on('message_sent', function(msg){// Just for testing purposes
console.log('Clent says: ' + msg);
});
socket.on('disconnect', function(){
console.log('Clent disconnected!');
});
});
我得到的只是客户端已连接!"和客户端已断开连接!"每当我尝试发送消息时. 这是在客户端上运行的脚本
All I ever get is "Client connected!" and "Client Disconnected!" whenever I try to send a message. And here's the script running on the client
<script>
var socket = io();
$('form').submit(function(){
socket.emit('message_sent', $('#usermessage').val());
$('#usermessage').val('');
return false;
});
</script>
正确解释为什么它不起作用将非常有帮助.
A proper explanation as to why this isn't working would be extremely helpful.
推荐答案
将脚本放置在<head>
标记内时,在进行DOM操作之前,应确保dom已经准备就绪,因为没有form
即可附加一个submit
事件;因此,将您的脚本包装在带有jQuery dom ready函数的地方:
When you place your script within <head>
tag, before DOM manipulation you should make sure that the dom is ready because without that there is no form
to attach a submit
event to it; so wrap your script whithin jquery dom ready function:
<script>
$(function() {
var socket = io();
$('form').submit(function(e){
e.preventDefault();
socket.emit('message_sent', $('#usermessage').val());
$('#usermessage').val('');
});
});
</script>
这篇关于提交表单时重新加载网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!