Dreekun
Dreekun

Reputation: 442

SyntaxError: Unable to parse bindings with json

I'm just starting with Knockout JS, and I'm having trouble finding what is wrong here. I'm calling a controller Web Service to get some data that I want to display in my page.

This is my ViewModel:

function ViewModel() {
    var self = this;

    self.MonthSalesList = ko.observableArray();

    var url = 'myurl';

    self.GetQueryData = function () {
        $.ajax({
            type: "GET",
            url: url,             
            dataType: "json",
            success: function (data) {
                console.log('callback success');
                console.log(data);
                var observableData = ko.mapping.fromJS(data);
                var array = observableData();
                self.MonthSalesList(array);
            },         
            error: function (jq, st, error) {
                alert(error);
            }           
        });
    }
}

$(document).ready(function () {
    ko.applyBindings(new ViewModel());
});

And in html:

<body>
    <table>
        <thead>
            <tr>
                <th>Year</th>
                <th>Mes</th>
                <th>Ano Atual</th>
                <th>Ano Anterior</th>
                <th>Variação</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: vendasMesList">
            <tr>
                <!-- <td data-bind="text: ko.toJSON($data)"></td> -->

                    <td data-bind="text: Year"></td>
                    <td data-bind="text: Mes"></td>
                    <td data-bind="text: Ano Atual"></td>
                    <td data-bind="text: Ano Anterior"></td>
                    <td data-bind="text: Variação"></td>

                </tr>
            </tbody>
        </table>
        <br/>
        <input type="button" value="Get Sales" data-bind="click: GetQueryData" />
    </body>

When I load the page and click on "Get Sales", I only get the first values of the json data:

enter image description here

The data I'm trting to get looks like this on Postman:

enter image description here

The only difference I see it's the numeric type of "Ano Atual".

Does anyone know what I'm doing wrong?

Thank you.

Upvotes: 0

Views: 38

Answers (1)

OfirD
OfirD

Reputation: 10490

You need to change these:

<td data-bind="text: Ano Atual"></td>
<td data-bind="text: Ano Anterior"></td>

...into these:

<td data-bind="text: $data['Ano Atual']"></td>
<td data-bind="text: $data['Ano Anterior']"></td>

That's ugly, but seems to be the way to go.

Upvotes: 1

Related Questions