簡體   English   中英

從JSON填充數據以進行下拉

[英]Populating data from JSON for drop downs

我正在從看起來像這樣的服務器接收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代碼中指定要檢索的數據,但是很多小時在線都沒有給出答案。

數據中的states鍵和dates鍵是數組,但是您嘗試將它們作為哈希值進行訪問。 如果要從狀態數組中提取狀態鍵,可以使用_.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哈希中使用數組,請改用函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM