这是我第一次尝试使用Knockout javascript。我很天真,所以请原谅我这个问题。
我有一个给出json响应的视图。
views.py
def get(self, request, code, format=None):
data = self.get_details(code)
paginator = Paginator(data, self.paginate_by)
page = request.GET.get('page', 1)
context = {}
try:
data_sent = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
data_sent = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
data_sent = paginator.page(paginator.num_pages)
context['data'] = self.get_user(chain_code)
context['page_object'] = data_sent.object_list
context['code'] = code
data = json.dumps(context, cls=DjangoJSONEncoder)
return HttpResponse(data)
我想使用此响应在我的django模板中的表格中填充 context ['data'] ,如下所示:
Id Name Status
1 xyz 1
2 abc 2
datalist.html
<script src="{% static "jsscript/datalist.js" %} "></script>
<div class = "container">
<div class = "page-header">
<!---all headers data --->
</div>
<div class="tab-content">
<table class="table table-bordered listingtable" >
<thead>
<tr>
<th style="width: 10%;">Id</th>
<th style="width: 10%;">Name</th>
<th style="width: 20%;">Status</th>
</tr>
</thead>
<tbody>
<!----script to populate table--->
</tbody>
</table>
我已经阅读了knockout.js的官方教程,但我不确定如何从我的API访问响应并填充模板中的表。
到目前为止我尝试过:
datalist.js
var ViewModel = function(data) {
var self = this;
self.Id = ko.observable(data.id);
self.Name = ko.observable(data.name);
self.status = ko.observable(data.status);
};
ko.applyBindings(new ViewModel(data));
我知道这个解决方案是完全错误的,但我只是不确定如何在正确的道路上前进,有人可以启发我吗?
答案 0 :(得分:2)
下面显示了当您从服务器获取数据时,如何在敲除时将数据填充为表格(您可以使用Ajax)。
示例:https://jsfiddle.net/kyr6w2x3/108/
HTML:
<table class="table table-bordered listingtable" >
<thead>
<tr>
<th >Id</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach:YourArrayList">
<tr>
<td data-bind="text:Id"></td>
<td data-bind="text:Name"></td>
<td data-bind="text:Status"></td>
</tr>
</tbody>
</table>
JS:
var yourData = [{id:1,name:"AAA" ,status:"AAA-status" },{id:2,name:"BBB" ,status:"BBB-status" },{id:3,name:"CCC" ,status:"CCC-status" }];
var MainViewModel = function() {
var self = this;
self.YourArrayList= ko.observableArray();
self.YourArrayList($.map(yourData, function (item) {
return new StatusItemViewModel (item);
}));
};
var StatusItemViewModel = function(data) {
var self = this;
self.Id = ko.observable(data.id);
self.Name = ko.observable(data.name);
self.Status = ko.observable(data.status);
};
ko.applyBindings(new MainViewModel ());