小编典典

为什么fetch()不起作用?

json

我正在尝试从JSON网址获取集合。骨干网确实发送了请求并得到了响应,但是models在它之后的集合中没有:

这是我的JavaScript:

stores.fetch();

响应中的JSON

[{"name":"Store 1"},{"name":"Store 2"},{"name":"Store 3"},{"name":"Store 4"}]

响应中的Content-Type HTTP标头为application/json

为什么不将其加载到集合中?JSON是否正确?

一些更多的代码:

be.storeList.Item = Backbone.Model.extend({
    defaults: {
        id: null,
        name: null,
        description: null
    },
    initialize:function(attrs){
        attrs.id = this.cid;
        this.set(attrs);
    }
});

be.storeList.Items = Backbone.Collection.extend({
    model: be.storeList.Item,
    url:'/admin/stores'
});

var stores = new be.storeList.Items();
stores.fetch();
console.log(stores.toJSON());

阅读 292

收藏
2020-07-27

共1个答案

小编典典

fetch是异步的。尝试

stores.fetch({ 
    success:function() {
        console.log(stores.toJSON());
    }
});

要么

stores.on("sync", function() {
    console.log(stores.toJSON());
});
stores.fetch();

要么

stores.fetch().then(function() {
    console.log(stores.toJSON());
});
2020-07-27