【问题标题】:Populating data from JSON for drop downs从 JSON 填充数据以进行下拉菜单
【发布时间】:2014-03-06 13:38:18
【问题描述】:

我正在从服务器接收 JSON,看起来像

{
    "accountType": ["Full","Trial"],
    "states": [
        {"state":"AL","stateDescription":"Alabama","featured":"A1"},
        {"state":"AK","stateDescription":"Alaska","featured":"B1"}
    ],
    "dates":[
        {"dateDescription":"Jan","month":1,"year":2008},
        {"dateDescription":"Feb","month":2,"year":2008}
    ]
}

在我正在做的主干文件中:

define([ 'backbone', 'underscore', 'vent', ], function (Backbone, _, vent) {
    'use strict';

    return Backbone.Model.extend({

        url: {},

        loaded: false,

        defaults: {
            accountType: [],
            states: [],
            dates: [],
        },


        initialize: function () {
            this.on('change', this.change);
            var that = this;

            $.getJSON("webapp/jsondata", function (data) {
                that.set({
                    states: data.states.state,
                });
            });

            $.getJSON("webapp/jsondata", function (data) {
                that.set({
                    dates: data.dates.dateDescription,
                });
            });

            $.getJSON("webapp/jsondata", function (data) {
                that.set({
                    accountType: data.accountType,
                });
           });
        },  
    });
});

所以每个$.getJSON 都应该获取相关数据并填充主干模型默认值。

目前只有account 类型有效。我不明白为什么这会起作用而其他人不会,因为它是相同的代码。唯一的区别在于 JSON 数据,accountType 有 2 条数据。 States 有 3 个,我只想退回其中的一个 (state)。

所以我想我的问题是在 $.getJSON 代码中指定要检索的数据,但在线很多小时都没有找到答案。

【问题讨论】:

    标签: javascript jquery json backbone.js marionette


    【解决方案1】:

    您数据中的statesdates 键是数组,但您尝试将它们作为散列访问。 如果你想从你的状态数组中提取状态键,你可以使用_.pluck

    $.getJSON("webapp/jsondata", function (data) {
        that.set({
            states: _.pluck(data.states, 'state')
        });
    });
    

    有了给定的数据,_.pluck(data.states, 'state') 就会给你["AL", "AK"]

    并非如所写,您的模型可以通过使用model.fetchmodel.parse 大大简化。例如:

    return Backbone.Model.extend({
        url: "webapp/jsondata",
        loaded: false,
        defaults: function () {
            return {
                accountType: [],
                states: [],
                dates: [],
            };
        },
    
        parse: function (data) {
            return {
                accountType: data.accountType,
                states: _.pluck(data.states, 'state'),
                dates: _.pluck(data.dates, 'dateDescription')
            };
        },
    
        initialize: function () {
            this.on('change', this.change);
            this.fetch();
        },  
    });
    

    注意在defaults 散列中使用数组,请改用函数。

    【讨论】:

    • 伙计,绝对做到了 - 完美,我对这个主干的东西完全陌生,我正在努力通过 - 你已经整理了一些我花了几个小时看的东西!干杯
    猜你喜欢
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2012-10-06
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多