Note: Make sure to replace 'your_api_endpoint' with the actual URL of your API endpoint. Additionally, you may need to include jQuery or another library for AJAX functionality if it's not already included in your project.
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.min.js"></script>
<title>Fetch data from RESTful API</title>
</head>
<body>
<div class="container my-4">
<div class="row">
<div class="col-12">
<div class="row row-cols-1 row-cols-md-3 g-4" data-bind="foreach: Data">
<div class="col">
<div class="card h-100">
<div class="card-header">
<span data-bind="text: id"></span>
</div>
<div class="card-body">
<a class="text-decoration-none" data-bind="attr: {href: $root.DataUrl()+'/' +id}">
<p class="card-title fs-5 fw-semibold" data-bind="text: title"></p>
</a>
<p class="card-text" data-bind="text: body"></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
function AppViewModel() {
var self = this;
// Observable array to hold fetched data
self.Data = ko.observableArray([]);
self.DataUrl = ko.observable("https://jsonplaceholder.typicode.com/posts");
// Function to make AJAX request
self.fetchData = function () {
$.ajax({
url: self.DataUrl(),
method: "GET",
dataType: "json",
success: function (response) {
// Update observable array with fetched data
self.Data(response);
},
error: function (error) {
console.log("error: ", error);
}
});
}
self.fetchData();
}
// Apply bindings when document ready
$(document).ready(function () {
ko.applyBindings(new AppViewModel());
});
</script>
</body>
</html>
I hope you understand clearly.
Thanks.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Making AJAX requests with Knockout.js is a common practice for fetching data from a server and updating the UI dynamically.
Here's a basic overview of how to do it:
Note: Make sure to replace 'your_api_endpoint' with the actual URL of your API endpoint. Additionally, you may need to include jQuery or another library for AJAX functionality if it's not already included in your project.
Complete Example
I hope you understand clearly.
Thanks.