Whenever i click that Add button it should fetch json data using ajax and should append that to my Observable arrray and in html also i want to append that.
Here is my code
function ProductViewModel() {
var self = this;
self.ProductList = ko.observableArray([]);
self.GetProducts = function (){
$.ajax({
type: "POST",
dataType: "json",
url: 'data.json',
//my json data is
//{"1":{"name":"user","productname":"hello"},"2":{"name":"user2","productname":"hello2"}}
success: function (data) {
console.log(self.ProductList());
self.ProductList($.map(data, function (product) {
return new ProductDetailsViewModel(product);
}));
}
});
}
self.GetProducts();
}
function ProductDetailsViewModel(data){
var self = this;
self.Name= ko.observable(data.name);
self.PrdouctName= ko.observable(data.productname);
}
ko.applyBindings(new ProductViewModel());
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js" charset="utf-8"></script>
<h1 data-bind="foreach:ProductList">
<div data-bind="text:Name"></div>
<div data-bind="text:PrdouctName"></div>
</h1>
Thanks in advance!