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
等
任何提示我錯過了什麼?
在我的情況下'rows'應該是可觀察的還是僅僅聲明爲'rows:data.entry'? – JackTheKnife
它取決於,如果您需要跟蹤並對其內容或計數進行雙向綁定,或者如果您計劃手動添加項目到該陣列,那麼我將它們作爲可觀察項。無論如何,knockout.mapping.js將爲您完成這項工作:D 對於數組操作檢查此:http://stackoverflow.com/questions/43920118/knockout-js-add-new-item-to-an-陣列/ 43922961#43922961 – baHI