Reputation: 2586
This is the first time I am trying my hands on Knockout javascript. I am very naive to it so excuse me for the question.
I have a view which gives a json response.
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)
I want to use this response to populate context['data'] in a table in my django template something like this:
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>
I have gone through the official tutorial of knockout.js, but I'm not sure how to access the response from my API and populate the table in the template.
What I have tried so far:
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));
I know this solution is completely wrong but I'm just not sure how to proceed in the right path, Can someone just enlighten me about it?
Upvotes: 0
Views: 561
Reputation: 3634
Below is showing how to populate your data as table in knockout when you get your data from the server (you may use Ajax).
Example: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 ());
Upvotes: 2