0

I'm trying to create my first node.js program with socket.io and I want to store the chat history and then when a user joins have the chat history pushed to his browser. I have the chat saving and pushing and the json that is sent looks like this:

[
    [
        {
            "username": "Warren2",
            "text": "Test"
        },
        {
            "username": "Warren2",
            "text": "Test2"
        },
        {
            "username": "Warren2",
            "text": "Test3"
        }
    ]
]

On my html page I have a javascript that has this

socket.on('updatehistory', function(data) {

}

The code that I put in there will be executed when the updatehistory message is pushed. I'm a n00b and pretty lost lol. This is what I tried:

socket.on('updatehistory', function (data) {
   $.each(json.results, function(username,text){
      $('#conversation').append('<b>'+ username + ':</b> ' + text + '<br>');
  });
});

This is the exact debug message for the updatehistory event from node.js

debug - websocket writing 5:::{"name":"updatehistory","args":[[{"username":"W
arren2","text":"Test"},{"username":"Warren2","text":"Test2"},{"username":"Warren
2","text":"Test3"}]]}

Can someone help me figure out how to parse that (preferable with jquery). Thank you :D

4

2 に答える 2

0

私はこのソリューションが大好きです: http ://www.rahulsingla.com/blog/2010/05/jquery-encode-decode-arbitrary-objects-to-and-from-json/

于 2012-07-03T21:06:30.650 に答える
0

すべてを自分で行いたい場合は、データをトラバースする方法を提供します。これはわずか 5 行のコードです。最初のコードは次のとおりです。サンプルで実際に機能することを示すために、ユーザー名とパスワードを警告しました。 .

http://jsfiddle.net/shivkumarganesh/gfff5/

 $(document).ready(function(){
        var k=[
    [
        {
            "username": "Warren1",
            "text": "Test"
        },
        {
            "username": "Warren2",
            "text": "Test2"
        },
        {
            "username": "Warren3",
            "text": "Test3"
        }
    ]
];

for(i in k)
    {
    var l=k[i];
     for (j in l)
    {
        alert("Username:"+l[j].username+" --  Message:"+l[j].text);
    }
    }​
    });

どちらJSON.parse()も機能していません$.parseJsonでした。だから私はこれが最善の解決策だと考えています。

于 2012-07-03T22:00:44.037 に答える