为什么取()不工作?(Why fetch() does not work?)

2019-06-24 12:28发布

我试图从一个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());

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


Answer 2:

得到你的项目类摆脱初始化函数的。 你不需要它。

还有,因为没有这样的事stores.models -如果你想看看里面有什么,你必须做console.log(stores.toJSON());



文章来源: Why fetch() does not work?