I am trying to create a table using Json response and Knockout.js
In Javascript
$(document).ready(function() {
$.ajax({
method : "POST",
url : "devTestServlet",
success : function(data) {
ko.applyBindings({
rows : data
});
}
});
});
In HTML first of all I imported scripts in header:
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<link rel="stylesheet" href="css/main.css" type="text/css"></link>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Then in body I did following:
<table >
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Date</th>
<th>Finish Date</th>
<th>Position</th>
</tr>
<tbody data-bind="foreach: rows">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: Start_Date"></td>
<td data-bind="text: Finish_Date"></td>
<td data-bind="text: Position"></td>
</tr>
</table>
Format of the data looks like following:
[
{
"id": "1",
"name": "Mike",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
},
{
"id": "2",
"name": "Jhon",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
},
{
"id": "2",
"name": "Jhon",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
}
]
This is my first program with Knockout.js so may be I am missing something. Could you please suggest ?
$.ajax returns the response as a string by default, knockout needs a JavaScript object. So you either have to specify dataType as JSON
$.ajax({
method: "POST",
url: "devTestServlet",
dataType: 'json',
success: function(data) {
ko.applyBindings({
rows : data
});
}
});
or do the conversion yourself
$.ajax({
method: "POST",
url: "devTestServlet",
success: function(data) {
ko.applyBindings({
rows : JSON.parse(data)
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With