I want to get the JSON sent from the server to the view in Knockout.js.

Asked 2 years ago, Updated 2 years ago, 79 views

Create a json called Employee on the server, pass the data to the screen as shown below, and
I'd like to get this data-employee from Knockout.js and display the edited data from Knockout.js in the table on the screen as editedList. How can I read this data from Knockout.js?

·HTML

<table id="table" data-employee={{Emplyee}}>
 <thead>
  <tr>
    <td>Name</td>
    <td>Last Name</td>
    .
    .
  </tr>
 </thread>
 <tbody data-bind="foreach:editedList">
  <tr>
    <td data-bind="text:firstName">/td>
    <td data-bind="text:secondName">/td>
    .
    .       
  </tr>
 </body>
</table>

·Knockout.js

//1. The process of retrieving Employee data here

// 2. Create data for listing using Employee data

// Bind the data created in 3.2 to the screen as follows
ko.applyBindings({
    editedList:
        { firstName: 'Bert', entryDate: 'xxxx-xx-xx'},
        { firstName: 'Charles', lastName: 'xxxx-xx-xx'},
        { firstName: 'Denise', lastName: 'xxxx-xx-xx'}
    ]
});

javascript knockout.js sails.js

2022-09-30 21:14

1 Answers

The answer is to pass the data-employee as a json string and the kockout side should be JSON.parse, but the way json is created depends on the server side language.
What are you using?

For example, rails would look like this
(Sumimasen, I don't have an environment at hand right now, so it's an image.
raw should be output without sanitization and escape_javascript should be needed to string json)

#sample.html.erb
<table id="table" data-employee='<%=escape_javascript(raw(@e-mployee.to_json)))%>'>

# sample.js
jsonString=$("#table").data("employee");
employee=JSON.parse(jsonString);


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.