Help me find a bug. There is a table:

<table> <thead> <tr> <th>Username</th> <th>Role</th> <th>First name</th> <th>Last name</th> <th>Email</th> <th>Notes</th> <th>Active State</th> </tr> </thead> <tbody id="user-list"> <script id="user-records" type="text/x-handlebars-template"> {{#each user}} <tr> <td>{{username}}</td> <td>{{role}}</td> <td>{{firstName}}</td> <td>{{lastName}}</td> <td>{{email}}</td> <td>{{notes}}</td> <td>{{activeState}}</td> </tr> {{/each}} </script> </tbody> </table> 

Template:

  var USER_METHOD ={ handlerData:function(resJSON){ var templateSource = $("#user-records").html(), template = Handlebars.compile(templateSource), studentHTML = template(resJSON); $('#user-list').html(studentHTML); }, loadUserData : function(){ $.ajax({ url:"/users", method:'get', success:this.handlerData }) } }; $(document).ready(function(){ USER_METHOD.loadUserData(); }); 

Well, the request itself:

 @RestController @RequestMapping("/users") public class UsersController { @Autowired private UserRepository repo; @RequestMapping(method=RequestMethod.GET) public List<User> getAll() { return repo.findAll(); } } 

Via Postman, the result is as follows:

  [ { "id": 1, "username": "admin", "password": "1234", "role": "ADMIN", "firstName": "alex", "lastName": "тест", "email": "alex@test.com", "notes": "test notes", "activeState": 1 } ] 

The problem is that the content in the table is not displayed and there are no errors in the browser either. Help me find what's wrong. Thank.

    1 answer 1

    To begin with ,
    That the template handlebars expects a javascript object, not a string.
    Therefore, you need to make sure that the result (which always flies over the network as a string) is parsed into a normal js-object.
    For this you need to tell jquery that the result of the query will be a JSON string
    dataType: 'json' .
    jQuery is of course smart and usually guesses on its own, but it's still best to make sure of that.

     $.ajax({ url:"/users", method:'get', success:this.handlerData, dataType: 'json' }) 

    Now to the point, with minimal edits to your code:

    Method 1: slightly change the pattern.
    {{#each user}} string on {{#each this}}

    Method 2: slightly change the transfer parameters when creating a template:
    Instead of studentHTML = template(resJSON); You need studentHTML = template({user: resJSON});

    As you can guess from the code, well, Handlebars do not know what the user and where to get it from your array to fill the template.
    In the first method, instead of "take user", we say "take this thing", in the second method, we tell what user .