質問

Whenever i am giving a single data element in my json file my code works fine,but as soon as i give an array of elements it starts showing undefined on the client side. This is my server side code.

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);
var fs= require('fs');
server.listen(3000);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/cli_index.html');
});

io.sockets.on('connection', function (socket) {
var file = __dirname + '/data.json';
  fs.readFile(file, 'utf8', function (err, data) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    data = JSON.parse(data);
  // You can save those values somewhere or just log them to the console
    console.log(data);
    socket.emit('news', { hello: data});
 });

  });

This is my client side code.

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {

 JSON.stringify(data);
  for(var i=0;i<2;i++){
   document.write(data[i].hello.name);
}
  });

</script>

This is my external json file.

[{"name":"hey"},{"name":"Gouraw"}]

役に立ちましたか?

解決

In this server side code:

socket.emit('news', { hello: data});

...you're sending the array as the hello property of an object, but this client-side code:

document.write(data[i].hello.name);

...is expecting the top-level to be an array, with individual hello properties for each entry. Change that to:

document.write(data.hello[i].name);

...so you're indexing into the array.

It would probably be best, as well, to limit your loop using the array's length rather than a hardcoded value:

 for(var i=0;i<data.hello.length;i++){
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top