这是我由C# JSON解析器生成的JSON字符串:
{
"NewDataSet": {
"Table": [
{
"ResultId": "1",
"AttachmentId": "1",
"AttachmentName": "Report1",
"RowsCount": "34",
"NotifyUserName": "william",
"InsBy": "developer",
"InsAt": "2012-12-07T17:28:01.46+08:00",
"IsNotify": "false"
},
{
"ResultId": "2",
"AttachmentId": "2",
"AttachmentName": "Report2",
"RowsCount": "37",
"NotifyUserName": "william",
"InsBy": "developer",
"InsAt": "2012-12-07T17:28:15.57+08:00",
"IsNotify": "false"
},
{
"ResultId": "3",
"AttachmentId": "3",
"AttachmentName": "Report3",
"RowsCount": "69",
"NotifyUserName": "william",
"InsBy": "developer",
"InsAt": "2012-12-07T17:28:25.58+08:00",
"IsNotify": "false"
}
]
}
}
然后我想将字符串解析为前端 JavaScript 以迭代值。我这样做了。
var jsonText;
$.ajax({
type: "POST",
url: "Default.aspx/MethodWithNoParameterJSON",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
//rulesName = dbtitle+msg.d;
//rulesCount = +msg.d;
jsonText = msg.d;
alert(jsonText.NewDataSet.Table[0].ResultId),
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
如何获取像jsonText.NewDataSet.Table[0].ResultId
这样的子元素数据?每当我调用alert(jsonText.NewDataSet.Table[0].ResultId)
时,它总是会提示空或未定义的对象。
为什么要使用 msg.d
来设置jsonText
变量?.d
属性从何而来?msg
参数应已是从 JSON 响应创建的对象。试试这个:
msg.NewDataSet.Table[0].ResultId
(请注意,您的jsonText
变量命名不正确:此时您拥有的不是 JSON 或"文本",它是一个对象 - 或者,在您的情况下,undefined
因为未定义msg.d
。但是您尝试将其用作对象,而不是 JSON。
错别字?我认为应该是
jsonText.NewDataSet.Table[0].ResultId // replace RulesId with ResultId