【问题标题】:Knockoutjs Options Binding with JSON data?Knockoutjs 选项与 JSON 数据绑定?
【发布时间】:2013-08-09 06:42:44
【问题描述】:

我正在尝试在淘汰选项绑定的帮助下从服务器列出 select 标记的选项。我有一个 PHP 页面,它返回 JSON 数据,该数据被推送到绑定到选择标记的淘汰赛可观察数组。但不知何故它不起作用,请参考以下代码:

HTML:

<div class="form-group">
    <select class="form-control">
        <option data-bind="options: Country_Names, optionsText: 'country_name'"></option>
    </select>
</div>

JavaScript:

$(document).ready(function(){
    function appModel(session_info){
        /* Session Info related bindings are commented as they are working fine */
        var self = this;
        this.Country_Names = ko.observableArray();

        // Bindings related to the batch processing
        $(function(){
            $.ajax({
                url:"../api/master_list.php",
                type:"get",
                data:{mastertype: '1'},
                cache:false,
                success:function(country_list){
                    ko.mapping.fromJSON(country_list, {}, self.Country_Names);
                }
            });
        });
    };

    $.ajax({
        url:"../api/sessions.php",
        type:"get",
        data: {rqtype: '1'},
        cache:false,
        success:function(session_info){
            var data = $.parseJSON(session_info);
            if (data.status == 'Invalid_id'){
                window.location.replace('../files/main.html');
            } else {
                ko.applyBindings(new appModel(session_info));
            }
        }
    });    
});

示例 JSON:

[{"country_name":"Albania"},{"country_name":"Chile"},{"country_name":"Cuba"}]

问题,为什么选择标签中没有列出选项?我错过了什么明显的东西吗?

【问题讨论】:

    标签: json knockout.js


    【解决方案1】:

    您正在对 option 元素进行数据绑定,而您想将绑定放在 select 上,如下所示:

    <select class="form-control" data-bind="options: Country_Names, optionsText: 'country_name'">
    </select>
    

    &lt;option...&gt; 元素消失了;选项将由 Knockout 生成。

    请注意,the relevant documentation 非常清楚这一切是如何工作的。如果您还没有,我建议(重新)阅读它。

    或者,查看这个完整的演示:

    var data = [{"country_name":"Albania"},{"country_name":"Chile"},{"country_name":"Cuba"}];
    
    ko.applyBindings({ Country_Names: data });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <select data-bind="options: Country_Names, optionsText: 'country_name'"></select>

    【讨论】:

    • @Max 好点。这就是为什么基本代码已经在问题中了。为了完整起见,我从记忆中(或者更确切地说:凭本能)重建了小提琴,并将其作为可运行的 sn-p 添加到答案中。 PS。可运行代码 is 或恕我直言,至少 应该 被认为是多余的,因为文档非常清楚所有这些是如何工作的。
    猜你喜欢
    • 2012-02-23
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2014-02-15
    • 2013-12-22
    • 2016-01-13
    相关资源
    最近更新 更多