gpt4 book ai didi

javascript - io.connect : io is not defined but socket. io 已加载

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

我构建了一个 node.js 服务器,它提供了一个 client.html 页面,其中包含来自 mysql 数据库的消息列表。我无法使用 ajax 调用使其工作。client.html页面是这样的:

        <time></time>
<div id="container">Loading ...</div>
<script src="http://oclock.dyndns.org:8000/socket.io/socket.io.js"></script>
<!--<script src="socket.io/socket.io.js"></script>-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

// create a new websocket
var socket = io.connect('http://oclock.dyndns.org:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
var msgs = '<div>';
$.each(data.flashmsgs,function(index,flashmsg){
msgs += "<b>Messaggio inviato da " + flashmsg.created_by + "</b><br>";
msgs += flashmsg.testo;
});
msgs += '</div>';
$('#container').html(msgs);

$('time').html('Last Update:' + data.time);
});
</script>

ajax调用的代码如下:

    (function nodeLoader(){
$.ajax({
url: "client.html",
method: "get",
data: {hk: hk },
success: function(data){
$('#messaggi').html(data);
}
});
})();

socket.io 代码已加载,但我在 io.connect 上收到错误:io 未定义。如果我将 url 从 client.html 更改为 http://oclock.dyndns.org:8000 ,也会出现同样的问题(正在监听请求的node.js服务器的url)。如有任何帮助,我们将不胜感激!

编辑:服务器.js

var hwkey;
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url'),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;

// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});

// creating the server ( localhost:8000 )
app.listen(8000);


function handler(req, res) {
var origin = (req.headers.origin || "*");
if (req.method.toUpperCase() === "OPTIONS"){
res.writeHead(
"204",
"No Content",
{
"access-control-allow-origin": origin,
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10, // Seconds.
"content-length": 0
}
);
return( res.end() );
}

console.log("INCOMING REQUEST: "+req.method+" "+req.url);
req.parsed_url = url.parse(req.url, true);
var getp = req.parsed_url.query;
hwkey = getp.hk;

fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(
200,
{
"access-control-allow-origin": origin,
"content-length": data.length
}
);
res.end(data);
});
}


function pollingLoop(){
// Doing the database query
var query = connection.query('SELECT id, testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'" AND letto="0"'),
//var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs'),
flashmsgs = []; // this array will contain the result of our db query

// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(flashmsg) {
// it fills our array looping on each user row inside the db
flashmsgs.push(flashmsg);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {

pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

updateSockets({
flashmsgs: flashmsgs
});
} else {

console.log('The server timer was stopped because there are no more socket connections on the app')

}
});
};


// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {

console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}

socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});

console.log('A new socket is connected!');
connectionsArray.push(socket);

});

var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
console.log(hwkey);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};

console.log('Please use your browser to navigate to http://localhost:8000');

最佳答案

好吧,我一开始就误会了。我刚刚调查了您的实时应用程序,看来您的 ajax 调用正在拉取整个 html 文档。

如果您通过 ajax 加载标记,然后插入现有页面,则您不需要完整的 HTML 文档。只需发送正文内容即可。

此外,socket.io 脚本引用最好位于父页面上,而不是通过 ajax 加载的页面上。

关于javascript - io.connect : io is not defined but socket. io 已加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681211/

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