【发布时间】:2019-01-07 12:19:15
【问题描述】:
我是 Knockout JS 的新手,我一直在尝试用 Ajax 请求的结果填充表格,但没有成功。我已经学习了几个教程和许多 Stack Overflow 问题,但我仍然没有得到我需要的结果。
我现在得到的错误是我的可观察数组没有定义。这是我的 JS 代码:
function FeatureRequest(data) {
if(data != null){
// console.log("Feature Request");
// console.log(data);
this.title = ko.observable(data.title);
this.description = ko.observable(data.description);
this.client_id = ko.observable(data.client_id);
this.client_priority = ko.observable(data.client_priority);
this.product_area_id = ko.observable(data.product_area_id);
this.user_id = ko.observable(data.user_id);
this.target_date = ko.observable(data.target_date);
this.ticket_url = ko.observable(data.ticket_url);
this.date_finished = ko.observable(data.date_finished);
}
}
function FeatureRequestViewModel() {
// Data
var self = this;
self.features = ko.observableArray();
console.log("Sending requests...");
$.getJSON("/api/obscure/request", function(response) {
var mappedFeatures = $.map(response, function(item) {
return new FeatureRequest(item)
});
self.features(mappedFeatures);
});
}
ko.cleanNode($("body")[0]);
var viewModel = new FeatureRequestViewModel();
ko.applyBindings(viewModel);
“未定义”的变量是 self.features 可观察数组。
这是我要填写的 HTML 表格:
<tbody id="featuresTable" data-bind="foreach:features">
<tr>
<td data-bind="text: features.title"> </td>
<td data-bind="text: features.description"> </td>
<td data-bind="text: features.client_id"> </td>
<td data-bind="text: features.client_priority"> </td>
<td data-bind="text: features.product_area_id"> </td>
<td data-bind="text: features.target_date"> </td>
<td data-bind="text: features.ticket_url"> </td>
<td data-bind="text: features.user_id"> </td>
<td class="single line">
<a class="edit ui icon violet button" value="features.id">
<i class="edit icon"> </i>
</a>
<a class="finish ui icon green button" value="features.id">
<i class="check icon"> </i>
</a>
<a class="delete ui icon red button" value="features.id">
<i class="delete icon"> </i>
</a>
</td>
</tr>
</tbody>
【问题讨论】:
-
拜托,你为什么需要
ko.cleanNode()?请看一下这个问题:stackoverflow.com/questions/15063794/…。 :-) -
在您的函数
FeatureRequest(data)中,如果data为空,则根本不会定义任何可观察对象。删除if可能会更好。 :-) -
我放了 ko.cleanNode() 因为否则我会得到一个错误:您不能将绑定多次应用于同一个元素。
-
我还添加了if子句,因为我的API返回的字段之一为null,如果我传递它,就会出错。
-
是的,您只能应用一次绑定。我希望你对此没有任何问题。 :-)
标签: javascript ajax knockout.js knockout-3.0