Knockout Mapping reading JSON

ε祈祈猫儿з 提交于 2019-12-11 08:47:04

问题


Just starting with KnockOut Mapping to read some JSON (using Google Books API) , but can't seem to get it to work. No errors report, but nothing is displayed. Probably a simple issue I overlooked, but thanks for the review.

Markup....

<body>
<h2>Find Cat in the Hat</h2>
   <div>
        <input id="booksearch" />
    </div>
    <div>
        <table>
            <thead>
                <tr>
                    <th>Volumes</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: model.items">
                <tr>
                    <td data-bind="text: model.id"></td>
                </tr>
            </tbody>
        </table>
    </div>
    <input id="btnTest" type="button" value="button" />
</body>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="/Scripts/knockout-2.2.0.js"></script>
<script src="/Scripts/knockout.mapping-latest.js"></script>

Jquery....

$(document).ready(function () {
    //Knockout Test

    $('#btnTest').click(function () {
        var url = "https://www.googleapis.com/books/v1/volumes?q=the+Cat+In+The+Hat";

        var viewModel = {};
        $.getJSON(url, function (data) {
            viewModel.model = ko.mapping.fromJSON(data);
            ko.applyBindings(viewModel);

        });
    });
});

回答1:


In the $.getJSON success callback you will get back a JavaScript object not a JSON string:

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response

So you need to use ko.mapping.fromJS(data); method instead of ko.mapping.fromJSON(data);

Your fixed code should look like:

$.getJSON(url, function (data) {
    viewModel.model = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

You also have an another issue in your view: data-bind="text: model.id" should be data-bind="text: id" you don't need the model there because inside the foreach you are in the context of model.items:

<tbody data-bind="foreach: model.items">
    <tr>
        <td data-bind="text: id"></td>
    </tr>
</tbody>

Demo JSFiddle.



来源:https://stackoverflow.com/questions/18863130/knockout-mapping-reading-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!