Reading C# dictionary in Javascript
You read like this:
alert(Chats["Sam"]);
(so like a C# Dictionary :-). You read/write to it using something like Chats["propertyName"]
)
or, to go through each value:
for (var c in Chats){ if (Chats.hasOwnProperty(c)) { alert(c + ' ' + Chats[c]); }}
Note that this is different than C#. In C# c
would contain a KeyValuePair<>
containing both the key and the value. In Javascript c
is only the key and to get the value you have to use Chats[c]
.
(the reasoning for hasOwnProperty
is here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)
Now... If you really want to split it:
var array = [];for (var c in Chats){ if (Chats.hasOwnProperty(c)) { array.push([c, Chats[c]]); }}
Just add the data type json to your ajax request
$.ajax({ url: "TextChatCalls/getChat.aspx", type: "POST", dataType: "json" context: document.body, success: function (response) { // do something with response });
This will make response
a javascript object that you can access like this
alert(response["sam"]) //How are you?
to split that up into a 2d array just do this
var Chats = [];for ( k in response ){ Chats[Chats.length] = [k, response[k]];}
I guess the important point here is that you properly understand what is going on on the JavaScript client side. The datatype that arrives on the JavaScript client side is a JSON string. JSON (= JavaScript Object Notation) can directly be interpreted by JavaScript.
A JavaScript object looks as follows:
var anObject = { name: "Sam", surname: "abc"};
You can access the properties of a JavaScript object either through a somewhat Dictionary-similar way like
anObject["name"] //will get "Sam"
or directly (property notation)
anObject.name
Instead a similar JSON string would look like
var aJsonString = '{ "name": "Sam", "surname": "abc"}'
Now to convert the JSON string to a JavaScript object you need to parse it. jQuery does this already for you, otherwise you can invoke JSON.parse(aJsonString)
and you'll get a valid JavaScript object.
Here I did a quick example: http://jsbin.com/adejev/2/edit