如何使用 fetch 将 json 添加到主干、js 集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8608184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:07:19  来源:igfitidea点击:

how to add json to backbone,js collection using fetch

jsonbackbone.js

提问by Cole Peterson

I am trying to get backbone.js to load json. The json loads but i am not sure how to get the items into my collection. Or maybe that happens automatically and i just can't trace out. scope issue?

我正在尝试让backbone.js 加载json。json 已加载,但我不确定如何将这些项目放入我的收藏中。或者这可能会自动发生,而我无法追踪。范围问题?

//js code

//js代码

//model
var Client = Backbone.Model.extend({
    defaults: {
        name: 'nike',
        img: "http://www.rcolepeterson.com/cole.jpg"
    },
});
//collection
var ClientCollection = Backbone.Collection.extend({
    defaults: {
        model: Client
    },
    model: Client,
    url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
    initialize: function () {
        this.collection = new ClientCollection();
        this.collection.bind("reset", this.render, this);
        this.collection.bind("change", this.render, this);
        this.collection.fetch();
    },
    render: function () {
        alert("test" + this.collection.toJSON());
    }
});
var myView = new theView();

//json

//json

{
    "items": [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]
}

回答by Esailija

Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:

您的 json 格式不正确,您可以修复 json 或在 parse 方法中向主干添加提示:

var ClientCollection = Backbone.Collection.extend({
    defaults: {
        model: Client
    },
    model: Client,
    url: 'json/client.json',

    parse: function(response){
       return response.items;
    }
});

Or fix your JSON:

或修复您的 JSON:

 [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]

回答by IvanM

If you use rest api, try turn off these parameters:

如果您使用rest api,请尝试关闭这些参数:

Backbone.emulateHTTP Backbone.emulateJSON

Backbone.emulateHTTP Backbone.emulateJSON