我在我的应用程序中安装了socket.io。但是,当我按下表单上的提交按钮时,页面将始终刷新。
我在Google和StackOverflow上看过这个问题,尝试了几种解决方案(例如确保我的套接字代码在$(文件).ready()...代码等内)但仍然没有骰子。
我可以简单地看一下console.log,说明我输入的数据值,以便该部分有效。
这是我的代码:
WWW
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('Webtech2:server');
var http = require('http');
//models
var Comment = require("../models/comments");
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
//Sockets komen hier
var io = require("socket.io")(server);
io.on("connection", function(socket) {
socket.on("postComment", function(data) {
console.log("Socket.io: server received POST");
//log data naar console
console.log("Client data log:"+data);
//stuur 'data' naar iedereen
io.sockets.emit("update_comment", data);
Comment.save(data, function(err,res) {
console.log(res+" added to DB");
io.emit('update:', res);
});
});
});
//op connection doe dit:
io.on("connected", function(socket) {
Comment.find().exec(function(err, output) {
socket.emit('show_data', output);
console.log("Output: "+output);
});
})
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
public / javascripts / sockets_comments.js(自定义名称)
//jquery voor sockets -- socket.io documentation/
$(document).ready(function() {
console.log("socket init ok");
var socket = io();
var result = "";
//data ophalen en naar mongod
$("#commentSubmit").on("click", function(e) {
var commentAuthor = $("#commentName").val();
var commentBody = $("#commentBody").val();
var commentDate = new Date();
//log van form data
console.log("Data opgehaald met waarde: "+commentAuthor+" als author, "+commentBody+" als bodyText en "+commentDate+" als tijdstip.");
//naar mongo
result = {
"cmt_author": commentAuthor,
"cmt_body": commentBody,
"cmt_date": commentDate
}.save;
//socket connect naar localhost op 3000 en post
var socket = io.connect("http://localhost:3000");
socket.emit("postComment", result);
console.log("Verzonden: "+result);
//reset inputs na send
$("#commentForm").val("");
});
//render
socket.on("updateComment", function(data) {
///
console.log("Data: "+data);
});
//loop visual data
socket.on("showData", function(output) {
//loop
for(var comments = 0; comments < output.length; comments++)
{
////
}
});
});
相关的玉视图文件
extends layout
block content
header
div.wrapper
a(href='/')
img(src="", alt="Logo")
a.hvr-grow(href="/discussions") All threads
span(style="color: white;") -
a.hvr-grow(href="/discussions/create") Start a new thread
div.pageContainer
h1 #{discussion.title}
span(id="categoryMarker" class="markers" style="font-size: 1.25em;") "#{discussion.category}"
span
a.hvr-grow(href="/discussions" style="float: right; margin-right: 25px;") Back to all threads
h3 Started by #{discussion.author}
| -
span Created on #{discussion.date.toDateString()}
span(style="display: none;") - #{discussion.location}
br
br
div#bodyText
p #{discussion.body}
div#commentsSection.pageContainer
form(action="" name="inputComment" id="commentForm")
input(id="commentName", placeholder="Your name" name="commentName" required)
br
br
input(id="commentBody", placeholder="Your comment" name="commentBody" required)
br
br
button(class="hvr-grow" type="submit" id="commentSubmit" style="color: black;") Post comment
script(src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js")
script(src="http://localhost:3000/socket.io/socket.io.js")
script(src="/javascripts/sockets_comments.js")
答案 0 :(得分:3)
您应该听取$("#commentForm").on("submit")
而不是$("#commentSubmit").on("click")
:
$("#commentForm").on("submit", function(e) {
var commentAuthor = $("#commentName").val();
// ...
return false; // don't forget to cancel the event too
});
编辑:这是一个通用的jsFiddle,证明了这一点:
您可以点击按钮,或按Enter键(这是submit
事件的美丽)。
答案 1 :(得分:3)
只需将e.preventDefault();
放在click
处理程序的开头:
$("#commentSubmit").on("click", function(e) {
e.preventDefault();
var commentAuthor = $("#commentName").val();
//...
});
顺便说一句,您不必在每次单击时连接到socket.io服务器。您应该只使用var socket = io();
进行一次连接,因此您可以删除此行:
var socket = io.connect("http://localhost:3000");
编辑:正如@lxe注意到的那样,实际上听一下表单的submit
事件会更好,因为它也可以拦截按Enter
键。