2017-09-04 82 views
-1

我需要幫助,在客戶端上顯示的對象屬性從MongoDB的對象發送到客戶端的socket.io

服務器

socket.on('question', (data) => { 
    Question.count().exec((err, count) => { 
    var random = Math.floor(Math.random() * count); 
    Question.findOne().skip(random).exec(
     function(err, data) { 
     socket.emit('data', { 
      question: data.question, 
      correctAnswer: data.correct_answer, 
      incorrectAnswer1: data.incorrect_answers[0], 
      incorrectAnswer2: data.incorrect_answers[1], 
      incorrectAnswer3: data.incorrect_answers[2] 
     }); 
     }); 
    }); 
}); 

客戶

socket.on('data', function(data) { 
    if (data) { 
    $('#questions').html(''); 
    $('#questions').append('<li>' + question + '</li>') 
    } 
}); 

$('#answer').on('click', function(e){ 
    e.preventDefault(); 
    socket.emit('question', {'data':$(this).serializeArray()}); 
}); 

I only get displayed this

我只得到顯示這

我想在下面顯示問題和答案

回答

1

你可以在你的data變量中獲得你的數據。所以你需要的每個信息都存儲在裏面。 使用console.log(data)來查看裏面的內容。始終顯示您獲得的內容。

我不知道你如何建立你的問題的對象,但這樣的事情應該在服務器的打印工作

socket.on('data', function(data) { 
    if (data) { 
    $('#questions').html(''); 
    $('#questions').append('<li>' + data.title + '</li>') 
    } 
}); 
+0

這增加了不確定,控制檯日誌對象。 – lejhbah

+0

在你的客戶端做一個console.log。 – sheplu

+0

好的tnx這個工程。它將數據存儲在另一個數據對象中,我不知道爲什麼。 @sheplu – lejhbah

相關問題