我正在尝试从API中检索数据后填充表格。
相关HTML:
<tbody data-bind="foreach: places">
<tr>
<td data-bind="text: clientName"></td>
<td data-bind="text: name"></td>
<td data-bind="text: address1"></td>
<td data-bind="text: address2"></td>
<td data-bind="text: city"></td>
<td data-bind="text: county"></td>
<td data-bind="text: country"></td>
<td data-bind="text: dateAdded"></td>
</tr>
</tbody>
JS:
function Place(data) {
this.clientName = ko.observable(data.ClientName);
this.name = ko.observable(data.Name);
this.address1 = ko.observable(data.Address1);
this.address2 = ko.observable(data.Address2);
this.city = ko.observable(data.City);
this.county = ko.observable(data.County);
this.country = ko.observable(data.Country);
this.dateAdded = ko.observable(data.DateAdded);
}
function PlaceListViewModel() {
var self = this;
self.places = ko.observableArray([]);
$.ajax({
type: "POST",
url: "SubscriberDashboard/SearchPlaces",
contentType: "application/json",
data: { "SearchTerm": "" },
success: function (data) {
var temp = [];
$.each(data.places, function (placeData) {
temp.push(new Place(placeData));
});
self.places(temp);
console.log(self.places());
}
});
}
ko.applyBindings(new PlaceListViewModel());
数据加载正常,ajax调用结束时的console.log显示Place对象数组。同样,会呈现适当数量的<tr>
元素,但<td>
元素中没有文字。
编辑:
function PlaceListViewModel() {
var self = this;
self.places = ko.observableArray([]);
$.ajax({
type: "POST",
url: "SubscriberDashboard/SearchPlaces",
contentType: "application/json",
data: { "SearchTerm": "" },
success: function (data) {
$.each(data.places, function (placeData) {
self.places.push(new Place(placeData));
});
console.log(self.places());
}
});
}
答案 0 :(得分:1)
您正在将索引传递给Place Model
而非实际数据。 $.each function
的第一个参数是index
,第二个参数是element
。
$。each()函数(整数索引,元素元素)。
最好让每个子模型var self = this
以避免冲突。
实施例:https://jsfiddle.net/kyr6w2x3/94/
$.each(data, function (index , placeData) {
self.places.push(new Place(placeData));
});