2017-05-11 74 views
0

我有一个问题,从嵌套的JSON对象的情况下返回JSON数据。KnockoutJS和从JSON对象绑定数据

HTML代码如下所示:

<table> 
<thead> 
    <tr> 
     <th>Name</th> 
     <th>DOB</th> 
     <th>Gender</th> 
     <th>Address</th> 
     <th>URL</th> 
    </tr> 
</thead> 
    <tbody data-bind="foreach: rows"> 
    <tr> 
     <td data-bind="text: resource.name[0].text"></td> 
     <td data-bind="text: dob"></td> 
     <td data-bind="text: gender"></td> 
     <td data-bind="text: address"></td> 
     <td data-bind="text: fullUrl"></td> 
    </tr> 
</tbody> 
</table>  

然后KnockoutJS

function PatientsViewModel() { 
     var self = this; 

     self.rows= ko.observableArray([]); 
     self.resources = ko.observableArray([]); 
     self.name = ko.observableArray([]); 
     self.text = ko.observable(""); 
     self.dob = ko.observable(""); 
     self.gender = ko.observable(""); 
     self.address = ko.observable(""); 
     self.fullUrl = ko.observable(""); 

     $.getJSON(
      "/proxy.php", 
      { 
       last: "john", 
       first: "smith", 
       dob: 19700101 

      }, 
      function (data) { 
       console.log(JSON.stringify(data.entry)); 
       self.rows(data.entry); 
      } 
     ); 

    } 

    ko.applyBindings(new PatientsViewModel()); 

和JSON响应结构如下:

[ 
    { 
     "fullUrl":"https://www.example.com/Patient/123", 
     "resource":{ 
     "resourceType":"Patient", 
     "id":"123", 
     "identifier":[ 
      { 
       "use":"official", 
       "type":{ 
        "coding":[ 
        { 
         "system":"http://hl7.org/fhir/v2/0203", 
         "code":"MR", 
         "display":"test data" 
        } 
        ], 
        "text":"test" 
       }, 
       "system":"1.2.3.4.5", 
       "value":"123", 
       "assigner":{ 
        "display":"PatientId" 
       } 
      } 
     ], 
     "active":true, 
     "name":[ 
      { 
       "use":"usual", 
       "text":"John Smith", 
       "family":[ 
        "Smith" 
       ], 
       "given":[ 
        "John" 
       ] 
      } 
     ], 
     "gender":"Male", 
     "birthDate":"1970-01-01", 
     "address":[ 
      { 
       "use":"home", 
       "type":"both", 
       "line":[ 
        "" 
       ], 
       "city":"", 
       "state":"", 
       "postalCode":"", 
       "country":"" 
      } 
     ] 
     }, 
     "search":{ 
     "mode":"match", 
     "score":0 
     } 
    } 
] 

,当我尝试绑定从JSON响应工作数据罚款只为fullUrl不能得到任何东西,如resource.name[0].text,resource.birthDate

任何提示我错过了什么?

回答

0

只需添加一些断点,我确定在使用getJSON获取数据之前,您需要执行KO绑定(请参阅:getJSON does not honor async:false)。

另一个问题可能是您获得的数据是JSON,并且不是可观察对象,但是您可以轻松帮助:var koViewModel = ko.mapping.fromJS(uiModel);但是你也需要这个JS库:knockout.mapping.js

+0

在我的情况下'rows'应该是可观察的还是仅仅声明为'rows:data.entry'? – JackTheKnife

+1

它取决于,如果您需要跟踪并对其内容或计数进行双向绑定,或者如果您计划手动添加项目到该阵列,那么我将它们作为可观察项。无论如何,knockout.mapping.js将为您完成这项工作:D 对于数组操作检查此:http://stackoverflow.com/questions/43920118/knockout-js-add-new-item-to-an-阵列/ 43922961#43922961 – baHI