挖空映射读取JSON [英] Knockout Mapping reading JSON

查看:92
本文介绍了挖空映射读取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅从KnockOut Mapping开始读取一些JSON(使用Google Books API),但似乎无法使其工作.没有错误报告,但是什么也不显示.我可能忽略了一个简单的问题,但感谢您的审查.

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.

标记....

<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 ....

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);

        });
    });
});

推荐答案

$.getJSON成功回调中,您将获得一个JavaScript对象而不是JSON字符串:

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

成功回调将传递返回的数据,通常为 由JSON结构定义并解析的JavaScript对象或数组 使用$ .parseJSON()方法.它还传递了的文本状态 响应

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

因此,您需要使用ko.mapping.fromJS(data);方法而不是ko.mapping.fromJSON(data);

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);
});

视图中还存在另一个问题:data-bind="text: model.id"应该为data-bind="text: id",您不需要在那里的model,因为在foreach中,您位于model.items的上下文中:

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>

演示 JSFiddle .

这篇关于挖空映射读取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆