2012-10-11 24 views
3

我正在处理的项目需要很多有关复杂XML文件的工作,因此我将它们转换为SimpleXML数组,JSON将其编码并通过Ajax将其传递给Knockout。KnockoutJS:绑定到具有非法名称的对象

问题是,几乎每个属性都有属性,SimpleXML插入一个名为@attributes的对象中。当我尝试绑定到它像myObject()[email protected],我得到一个错误

Message: SyntaxError: Unexpected token ILLEGAL; 
Bindings value: text: alertObj()[email protected] 

我已经试过'@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" 
      }; 

我想避免改变任何结构和名称。

我怎样才能得到这个工作?

回答

5

那是因为它不是一个有效的JavaScript变量名:

标识符必须以$,_,或以Unicode 类别“大写字母(陆)”任何字符,“小写字母(Ll)“, ”Titlecase letter(Lt)“,”Modifier letter(Lm)“,”Other letter(Lo)“, 或”Letter number(N-1)“。

http://mathiasbynens.be/notes/javascript-identifiers

变量名称不能以@开头,因此你看到的错误。添加单引号,括号或其他任何内容都没有意义。变量名称无效,您需要更改从服务器返回数据的方式。

+0

这很有道理。在json编写它之前,我将在服务器端修改数组。谢谢。 – solefald

1

我遇到了类似的问题,我完全同意你应该改变数据从服务器返回的方式。但是,如果您确实无法控制数据或暂时无法控制数据,则可能会呈现您想要使用的内容:

$data['@attributes'].Name 
相关问题