【发布时间】:2013-07-12 22:06:36
【问题描述】:
我正在将一些模型数据编码成这样的 html 元素:
@Html.Raw(Json.Encode(Model));
返回的 json 字符串如下所示:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
当我尝试使用 JSON.parse 解析这个时,我得到一个错误:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
如何将此jsonTestList 字符串转换为javascript 数组,以便可以正确访问arrayTestList 的元素?
编辑:
抱歉,我忘了提及我的编辑。基本上上面的javascript代码在部分视图2中。我对模型进行json编码的代码在另一个部分视图1中。从PV 2,我无法访问PV 1的模型对象,所以我只是将内容转储到div 标签,这样我就可以访问这个列表 TestList 元素。
【问题讨论】:
-
请注意,使用”(假设您的 json 写在 div 元素中)。当它被输出时,它将关闭你的开始 div 元素,然后浏览器会将以下脚本标记解释为 html dom 的一部分并运行其中的任何内容。
Html.Raw是危险的。如果你的 json 对象的字段没有被清理,你就有可能受到 XSS 攻击。例如。将您的TestDescr属性之一设置为“
标签: javascript jquery asp.net-mvc json razor