包括不会从数组返回数据

时间:2016-05-29 08:18:15

标签: json node.js socket.io

早安,

我有一个问题/问题我正在构建的脚本,我使用include来建模我的数组并将它们返回给server.js

数据显示到控制台,但不显示给访问者,在一个简单的网页上,如果我将查询和我的建模放在server.js文件中,它有效,有人有理由说明为什么包含不会返回结果查询?

Server.js

 var io = require('socket.io').listen(3000);
 var data_model = require("./data_model.js");
 io.sockets.on('connect', function(socket) {
 console.log('There is a connection');
 io.emit("data", "There is a connection");
 console.log(data_model.retrieve()); // THIS LINE WORKS, 
socket.emit("dataretrieve", JSON.stringify(data_model.retrieve()));
});

我的数据模型

var mysql = require('mysql');
    var connection = mysql.createConnection({
    host: "",
    user: "",
    password: "",
    database: ""
   });


var data_model = {

    retrieve: function() {

    connection.query('SELECT * FROM data_retrieve', function(err, rows, fields, data) {

            if (rows.length === 0) {

            } else {

                dataretrieve = {};

                dataretrieve["data_retrieve"] = {};

                dataretrieve["data_retrieve"] = {
                    id: rows[0].id,
                    msg: rows[0].msg
                };

                return JSON.stringify(dataretrieve);

            }

        });
    }
};

module.exports = data_model;

当前网页:

 <script   src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">      </script>
<script src="http://172.0.2.13:3000/socket.io/socket.io.js"></script>
<script>
    $(document).ready(function(){
    var socket = io.connect('http://172.0.2.13:3000');
    socket.on('data', function(data){

    document.getElementById('connection').innerHTML = data;

    });
    socket.on('dataretrieve', function(dataretrieve){
    console.log(dataretrieve); //WONT SHOW THE DATA
    });

    });
</script>
<body>
    <pre>
<div id="connection"></div>
  <div id="dataretrieve"></div>

1 个答案:

答案 0 :(得分:0)

var data_model = {

    retrieve: function(cb) {

    connection.query('SELECT * FROM data_retrieve', function(err, rows, fields, data) {

            if (rows.length === 0) {

            } else {

                dataretrieve = {};

                dataretrieve["data_retrieve"] = {};

                dataretrieve["data_retrieve"] = {
                    id: rows[0].id,
                    msg: rows[0].msg
                };

                cb(JSON.stringify(dataretrieve));

            }

        });
    }
};

更改从

调用检索的代码
socket.emit("dataretrieve", JSON.stringify(data_model.retrieve()));

data_model.retrieve(function(data){
    socket.emit("dataretrieve",data);
})