我建议使用Socket.IO
服务器端代码
var io = require('socket.io').listen(80); // initiate socket.io server
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' }); // Send data to client
// wait for the event raised by the client
socket.on('my other event', function (data) {
console.log(data);
});
});
和客户端
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost'); // connec to server
socket.on('news', function (data) { // listen to news event raised by the server
console.log(data);
socket.emit('my other event', { my: 'data' }); // raise an event on the server
});
</script>
或者,您可以使用路由器功能,该功能根据客户端的特定请求调用某些功能
var server = connect()
.use(function (req, res, next) {
var query;
var url_parts = url.parse(req.url, true);
query = url_parts.query;
if (req.method == 'GET') {
switch (url_parts.pathname) {
case '/somepath':
// do something
call_some_fn()
res.end();
break;
}
}
})
.listen(8080);
并使用 JQuery 触发AJAX
请求
$.ajax({
type: 'get',
url: '/somepath',
success: function (data) {
// use data
}
})