0

已解决:答案是:socket.on('clients', function(data) { document.write(JSON.stringify(data)); });

我想在屏幕上以 JSON 形式获得这样的输出(只有粗体部分):

调试 - websocket 写入 5::: {"name":"clients","args":[[{"id":6,"name":"demo 3"},{"id":7,"name" :"demo1"}]]}

我一定遗漏了一些东西,因为我无法理解为什么它不打印为 JSON。我有 3 个文件:

app.js(服务器):

var fs = require('fs');
var db = require("./db.js");

var http = require('http').createServer(function handler(req, res) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        } else {
            res.writeHead(200);
            res.end(data);
        }
    });
}).listen(3000);
// -----------------------------------
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (client) {
    console.log('Client connected');
    db.get_employees(function (employees) {
        io.sockets.emit('clients', employees);
    });
});

db.js(连接到数据库):

// -----------------------------------
var mysql = require('mysql');
var client = mysql.createConnection({
    user: 'xxxx',
    password: 'yyyy',
    host: '123.45.67.89',
    database: 'zzzz'
});
// -----------------------------------
exports.get_employees = function (callback) {
    client.query("select id, name from clients", function (err, results, fields) {
        callback(results);
    });
}

index.html

<script src="http://192.168.2.25:3000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script>
 $(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
   $.each(data, function(i, obj) {
        //  document.write(obj);      // Gets me [object Object][object Object]
        //  document.write(obj.name)  // Gets me name column
        //  document.write(obj.email) // Gets me email column
        //  document.write(obj.xxxxx) // Gets me xxxxx column
        //  document.write(JSON.stringify(obj));   //Prints as JSON but structure is   wrong and it is a html string not as JSON output

     });
  });
});
</script>

我无法弄清楚为什么我不能将它打印为 JSON。请参阅 index.html 注释行。我也希望它是我数据库的干净 JSON 输出,而不是 html。

io.sockets.emit('clients', employees); 在 App.js 中发出我想要的正确 json 格式,但我无法输出它。我得到 [Object Object] 或未定义。必须有办法做到这一点,因为如果我必须手动构建它,它会使其速度效率低下。

任何帮助,将不胜感激。

4

1 回答 1

1

这是因为您自己输出每个 JSON 对象。尝试对“数据”变量进行字符串化,例如

$(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
    document.write(JSON.stringify(data));
  });
});
于 2013-06-25T11:49:39.720 回答