[Answered ]-KO: Error when parsing JSON

1πŸ‘

βœ…

There is nothing wrong with your sample code you provided except the part you have this.body = ko.observable(data.responseText) while your data does not contain a responseText in your sample commentData object . if you replace commentData object with var commentData = {"responseText":"-->Body here<--"} it works.

Note: this part

 <span data-bind="foreach: { data: comments(), as: 'comments' }"> 
         <p data-bind="text: comments.body"></p> // comments.body => body
    </span>

on your question is wrong but you have it correct on your sample code .It should be

 <span data-bind="foreach: { data: comments(), as: 'comments' }"> 
         <p data-bind="text: body"></p>
    </span>

Here is a working version of your sample :https://jsfiddle.net/rnhkv840/26/

1πŸ‘

I assume you are using Django Rest Framework, so the JSON structure you get for your posts is done automatically by your serializer based on your model fields.

Back to the frontend, I have not used knockout js before, but what you require is to load the comments using another controller. Either you do it one by one using the links provided by your main resource (this can result in lots of queries sometimes), or you create a filter on your comments endpoint which will allow you to retrieve comments for a specific post.

πŸ‘€nezhar

0πŸ‘

Ever considered using the django REST framework? It can help you serialize all you models with a simple viewset. Check out the docs.

πŸ‘€Bogdan

0πŸ‘

So found the actual problem. The way the JavaScript read the data from the server, ment that since there was only one value for the comments, the data property of a comment was the variable storing the body of the comment. Not the data.body.

πŸ‘€H. Boe

Leave a comment