I have a JSON string that I need to convert into a knockout.js observable array.
Here is the JavaScript code I am currently using:
$(document).ready(function(e){
var model = function(dat){
this.tabledata = ko.observableArray(dat);
};
$.ajax({
url: 'http://localhost:1141/rest_service/show_data',
type: 'GET',
success: function(msg){
// var dat = JSON.parse(msg);
alert(msg);
ko.applyBindings(new model(msg));
},
error: function(msg){
alert(JSON.stringify(msg));
},
});
});
And here is the HTML structure:
<table id = "example" >
<thead>
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Status</th>
<th>Date of birth</th>
<th>Age</th>
</tr>
</thead>
<tbody data-bind='foreach: tabledata'>
<tr>
<td data-bind='text: $parent.empId'/></td>
<td data-bind='text: $parent.empStatus'/></td>
<td data-bind='text:$parent.dob'/></td>
<td data-bind='text: $parent.empName'/></td>
<td data-bind='text: $parent.age'/></td>
</tr>
</tbody>
</table>
After making an ajax call, I receive a JSON response from the server and I want to bind this data to an HTML table.
I attempted to use ko.mapping.fromJs()
to convert the JSON to an observable array but encountered the following error:
Error: The argument passed when initializing an observable array must be an array, or null, or undefined.
The JSON response looks like this:
[
{"empId":100,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":101,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":102,"empName":"TATA","empStatus":"yes","dob":"1997-12-12","age":18},
{"empId":103,"empName":"kljh","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":111,"empName":"Aria","empStatus":"No","dob":"1995-10-17","age":20}
]
What adjustments can be made to the code to ensure the proper conversion of the JSON string into a Knockout.js observable array?