gpt4 book ai didi

javascript - 无法在 Node js 教程中提交表单

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:47 24 4
gpt4 key购买 nike

我正在做这个 http://socket.io/get-started/chat/

我在“发出事件”部分

当我在文本框中输入消息并点击“发送”时,它会刷新页面并将我带到该网址本地主机:3000/?而不是在服务器上记录消息。

为什么按钮无法触发 $('form').submit(function(){ 行?

如果我在chrome上打开JS控制台并输入

socket.emit("chat message", 'testing from console')

它按预期在我的命令行服务器窗口中记录消息。所以我不认为服务器端代码有错误。

我手写了所有内容,但当它不起作用时,我复制粘贴以确保我输入正确。

所以index.html对我来说是

<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<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>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>

index.js 是

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http)

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});

http.listen(3000, function(){
console.log('listneing on *:3000')
});

使用 Chrome 版本 47.0.2526.80(64 位)

最佳答案

尝试将代码包装在文档就绪 block 中。该表单可能尚不存在。

$(function(){
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});

关于javascript - 无法在 Node js 教程中提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34377170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com