我正在从事的项目需要大量处理有点复杂的 XML 文件,因此我将它们转换为 SimpleXML 数组,对其进行 JSON 编码并通过 Ajax 将其传递给 Knockout。
问题是几乎每个属性都有属性,SimpleXML 将其插入名为 @attributes
的对象中。当我尝试像 myObject().@attributes.Name
一样绑定(bind)到它时,出现错误
Message: SyntaxError: Unexpected token ILLEGAL;
Bindings value: text: alertObj().@attributes.Name
我已经尝试过 '@attributes', ['@attributes'], [@attributes]
但没有任何效果。我还尝试了各种转义字符和 unicode 转义符。
这是 json 的样子:
var alertObject =
{
"@attributes":
{
"DescriptionContentType":"text\/plain",
"Description":"",
"IsActive":"true",
"Name":"Apache Requests Per Interval"
},
"Frequency":
{
"PeriodInSeconds":"60"
},
"MetricLevelNotification":"false",
"AlertTriggerMode":"2",
"CautionActionDelay":"0",
"DangerActionDelay":"0",
"CautionActionList":
{
"ActionID":
{
"ManagementModuleName":"Base Module",
"ConstructName":"Base SMTP Mail Action"
}
},
"DangerActionList":
{
"ActionID":
{
"ManagementModuleName":"Base Module",
"ConstructName":"Base SMTP Mail Action"
}
},
"MetricGroupingID":
{
"ManagementModuleName":"Base Module",
"ConstructName":"Apache Requests Per Interval"
},
"AlertCombineOperator":"1",
"AlertCompareOperator":"2",
"CautionTargetValue":"2000",
"DangerTargetValue":"15000",
"CautionMinNumPerPeriod":"3",
"CautionAlertPeriod":"6",
"DangerMinNumPerPeriod":"1",
"DangerAlertPeriod":"1"
};
我想避免以任何方式更改结构和名称。
我怎样才能让它工作?
最佳答案
那是因为它不是一个有效的 javascript 变量名:
An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.
来自 http://mathiasbynens.be/notes/javascript-identifiers
变量名不能以 @ 开头,因此您会看到错误。附加单引号、括号或其他任何内容都没有意义。变量名称根本无效,您需要更改从服务器返回数据的方式。
关于javascript - knockout JS : Binding to objects with illegal names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12832080/