我在 C# (ASP.NET) 中有一个字典变量。我想将此数据发送到 Javascript。我正在使用此代码对其进行序列化并发送到 javascript。
Dictionary<string, string> chat;
chat = new Dictionary<string, string>();
chat.Add("Sam", "How are you?");
chat.Add("Rita", "I am good");
var serialize = new System.Web.Script.Serialization.JavaScriptSerializer();
Response.Write(serialize.Serialize(chat));
在 Javascript 页面上,我正在调用此页面;
$.ajax({
url: "TextChatCalls/getChat.aspx",
type: "POST",
context: document.body,
success: function (response) {
var Chats = response.split('\n')[0];
alert(Chats);
}
});
聊天 var 中的值是 {"Sam":"How are you?","Rita":"I am good"}
我不知道如何在聊天中读取此值。我能否以任何方式将其转换为二维数组并将其读取为数组[0][0]、数组[1][0] 等?
谢谢。
编辑: 另一个困惑是,从 ASP.NET 返回的响应对象包含
{"Sam":"How are you?","Rita":"I am good"}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="getChat.aspx?Id=141755" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZJctiKZK4rXVndR3mbGssIarCrOF" />
</div>
<div>
</div>
</form>
</body>
</html>
不仅是 {"Sam":"How are you?","Rita":"I am good"}
如预期的那样。因此,我必须通过 var Chats = response.split('\n')[0];
拆分响应对象,这使它成为一个字符串!
最佳答案
你这样读:
alert(Chats["Sam"]);
(就像 C# 字典 :-)。您可以使用类似 Chats["propertyName"]
的方式对其进行读/写)
或者,遍历每个值:
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
alert(c + ' ' + Chats[c]);
}
}
请注意,这与 C# 不同。在 C# 中 c
将包含 KeyValuePair<>
包含键和值。在 Javascript 中 c
只是关键,要获得必须使用的值 Chats[c]
.
(hasOwnProperty
的推理在这里 http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ )
现在...如果你真的想拆分它:
var array = [];
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
array.push([c, Chats[c]]);
}
}
关于javascript - 在 Javascript 中读取 C# 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7776337/