繁体   English   中英

Node.js / Socket.io / Mysql打印为JSON

[英]Node.js / Socket.io / Mysql to print as JSON

已解决:答案是: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('客户',雇员); App.js中发出我想要的正确json格式,但无法输出。我得到了[Object Object]或Undefined。 必须有一种方法可以执行此操作,因为如果我必须手动对其进行结构化,则会使其速度降低。

任何帮助,将不胜感激。

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

$(document).ready(function() {
  var socket  = io.connect('http://192.168.2.25:3000');
  socket.on('clients', function(data) {
    document.write(JSON.stringify(data));
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM