为什么 fetch() 不起作用? [英] Why fetch() does not work?

查看:50
本文介绍了为什么 fetch() 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to fetch a collection from a JSON url. The backbone does send the request and does get a response but there are no models in the collection after it:

这是我的 JavaScript:

Here is my JavaScript:

stores.fetch();

响应中的 JSON

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

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

The Content-Type HTTP header in the response is application/json.

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

Why doesn't it load into the collection? Is the JSON correct?

更多代码:

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

推荐答案

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

这篇关于为什么 fetch() 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆