Getting the JSON response in Knockout JS may require specific steps and techniques. Here

I'm trying to extract an array from a JSON file and use it with Knockout.js. I've written the following code but can't seem to get the desired response. Can anyone help me out? Here's my approach:

Inside JSP

<table id="timesheets" class="table table-striped table-hover table-condensed">   
<thead>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Month</th>
        <th>Year</th>
    </tr>
</thead>
   <tbody data-bind="foreach: viewModel.timesheets">
    <tr>
        <td data-bind="text: firstname"></td>
        <td data-bind="text: lastname"></td>
        <td data-bind="text: month"></td>
        <td data-bind="text: year"></td>
    </tr>
</tbody>
 </table>

Within Script

<script>
 $(function () {
    ko.applyBindings(viewModel);
    viewModel.loadTimesheets();
});
function timesheet(timesheet) {
    this.id = ko.observable(timesheet.id);
    this.firstname = ko.observable(timesheet.firstname);
    this.lastname = ko.observable(timesheet.lastname);
    this.month = ko.observable(timesheet.month);
    this.year = ko.observable(timesheet.year);
}
var viewModel = {
    timesheets: ko.observableArray([]),

loadTimesheets: function () {
    var self = this;
    $.getJSON("/content/personal/test0/jcr:content/content-page/horizontalline.json",function (timesheets) {
            self.timesheets.removeAll();
            $.each(timesheets, function (index, item) {
                self.timesheets.push(new timesheet(item));
            });
        }
    );
}
};

</script>

Within JSON File

<%@page session="false" %>
<%@ page import="org.apache.sling.jcr.api.SlingRepository" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.day.cq.commons.TidyJSONWriter,
    com.day.cq.tagging.Tag,
    java.util.Locale,
    com.day.cq.wcm.api.WCMMode,
    com.day.cq.tagging.TagManager,
    com.day.cq.tagging.TagCloud" %>

... additional JSON processing logic here ...

%>

If you could provide any assistance regarding this issue since I am fairly new to using Knockout.js, it would be greatly appreciated.

Answer №1

Here is the required structure for your script

function schedule(timesheet) {
    this.id = ko.observable(timesheet.id);
    this.firstname = ko.observable(timesheet.firstname);
    this.lastname = ko.observable(timesheet.lastname);
    this.month = ko.observable(timesheet.month);
    this.year = ko.observable(timesheet.year);
}
var dataModel = {
    timesheets: ko.observableArray([]),
    fetchTimesheets: function () {
        var self = this;
        $.getJSON("/content/aib/personal/test0/jcr:content/content-page/horizontalline.json",function (timesheets) {
                self.timesheets.removeAll();
                self.timesheets(timesheets)
            }
        );
    }
};

 $(function () {
    ko.applyBindings(dataModel);
    dataModel.fetchTimesheets();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Bootstrap navigation bar drop-down feature is not displaying the menu

After skimming through various threads on stackoverflow regarding the dropdown box in the navigation bar, none of the solutions seem to address my issue. Utilizing bootstrap version 3, I've implemented the provided navbar example from the official si ...

picker and calculator for selecting date ranges

I'm currently working on a hotel booking form where prices are calculated based on the number of adults, seniors, and students. I'm trying to add a date range picker feature that will determine the total cost depending on the selected number of d ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Enhancing jQuery Rating Plugin

Currently, I am working on customizing the jQuery Bar Rating System Plugin. You can view an example of the plugin by visiting this link: . The rating system on my end will resemble Example D. Rather than having the plugin based on user input, my goal is to ...

What is the best way to access the references of 'child controllers' in NavigatorIOS within a React Native app?

After diving into react-native for the past few days, I've encountered a dilemma regarding the NavigatorIOS component. Is there a way to access and manipulate 'child controllers' of NavigatorIOS similar to how it's done in native object ...

Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience. For instance, the polyfill fitie b ...

Choosing a random element in React: A step-by-step guide

I'm currently working on a dynamic website that aims to load a random header component upon each refresh. Despite my various attempts, the functionality operates smoothly during the initial load but consistently throws this error on subsequent refresh ...

I wonder why serialize() is not returning a response to me

As someone who is just starting to learn jQuery, I've been experimenting with the .serialize method in jQuery. Unfortunately, I haven't had much luck getting it to work properly. Despite connecting to the latest library (version 3.4.1) and checki ...

Conversion of an NSNumber to an NSString using stringValue method encounters an error

I recently came across a situation where I encountered an error in my code that I couldn't quite figure out. While browsing through similar questions on SO, I found one that seemed relevant but didn't quite match my scenario. The problematic lin ...

Integrate OAuth1 GET request in Node.js and React to enhance security and access control

Looking to integrate the following details into my React website using Axios, JavaScript, node: GET request URL: Type: OAuth 1.0 SignatureMethod: PlainText ConsumerKey: CK ConsumerSecret: CS AccessToken: AT TokenSecret: TS Include authorization data in ...

In an MVC 4 application, when using JQuery to replace HTML and then calling the .show() function, the

I have a null div element: <div id="reportBody"></div> with basic styling: #reportBody { height: 100%; } The reportBody div is located within a hidden modal that is triggered by a button click. I am using jQuery and AJAX to call a contro ...

Guide to accessing a server file directly from the client's web browser

Hey Team, I have a requirement for the browser to read a property file from the server. To achieve this, I am using JQuery/AJAX as shown below. <script> var properties = null; $(document).ready(function(){ $.ajax({url:"demo_test.txt",success:fun ...

jQuery getJSON is returning an empty output

I have been attempting to integrate JSON data into my HTML file using jQuery. However, I am not getting any output in my HTML page, not even null or undefined When I tried using external JSON data from Flickr, all I could see was [Object] Even when test ...

I am facing issues with my setInterval function, it seems to be malfunctioning on Google Chrome

As a new programmer, I am currently diving into the world of OOP in JavaScript. I have some basic code for a flashing cursor, but it's not functioning as expected. When the page loads, the cursor just remains static on the screen without any changes. ...

How to dynamically set a radio button as checked or active based on the current state value

Currently, I have a header that rotates through 4 images every 5 seconds. Users can manually cycle through these images using 5 radio buttons. The styling for the active/checked radio button is only applied when users click on it themselves. However, if t ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Tips on adjusting my script to focus on particular text within a div in HTML

I'm currently learning how to code and working on a text generator that allows users to edit text and export it as .DOCX. I came across this script called jsfiddl on the website npmjs, which enables exporting HTML to .DOCX. However, I'm having tr ...

Interchanging JSON and XML formats in C/C++ programming

I've been exploring various options but have yet to find a reliable set of routines for converting between JSON and XML in C or C++. While I've come across solutions in Javascript, Java, PHP, and Python, my json library is json-spirit. Currently ...

Vue Router Issue: Unable to Navigate to Different Routes, Always Redirected to Home Page

I am currently working on a Vue 3 project and am facing an issue with the Vue Router not displaying the correct routes. Whenever I try to navigate to routes such as /cars or /admin, the URL does not update and the application stays on the home page. import ...

What is the purpose of using bind in this particular code snippet?

While following the introductory tutorial, I came across a certain line that is confusing: db.on('error', console.error.bind(console, 'connection error:')); You can find it in this guide. Wouldn't it be simpler to just use db. ...