将有效的json文件拉入Backbone.js集合会导致错误

时间:2015-06-24 01:18:52

标签: javascript json backbone.js

当我尝试获取集合时,我什么也得不到,并且触发了我的获取请求中的错误子句。这就是我的收藏和模型的样子:

window.Codetest.Models.Post = Backbone.Model.extend({
    defaults:{
        id: null,
        userId: null,
        date: null,
        content: null,
        comments: []
    }
});


window.Codetest.Collections.Posts = Backbone.Collection.extend({
    url: "posts.json",
    model: Codetest.Models.Post
});

Codetest.Collections.posts = new Codetest.Collections.Posts();
Codetest.Collections.posts.fetch({
success: function(data) {
     console.log(data);
  },
  error: function(){
     console.log('error');
  } 
});

我从posts.json文件中提取这样的帖子,该文件与我的javascript文件位于同一目录中:

[
    {
        "id": 1,
        "userId": 1,
        "date": "",
        "content":"Love wine? Love food? Love to win an iPad 2 with gift certificates to your favorite IA winery & Dine IA restaurant. http://bit.ly/xQ4Ls8",
        "comments": [
            {
                "id": 13,
                "postId": 1,
                "userId": 3,
                "date": "",
                "content": "Would you happen to know were Capone is? Since you are a secret agent and all"
            }

        ]

    },
    {
        "id": 2,
        "userId": 3,
        "date": "",
        "content":"Day 2 of house sitting...awww my firends really do Trust me!",
        "comments": []

    }
]

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果posts.json文件位于同一目录中,请使用以下命令:

window.Codetest.Collections.Posts = Backbone.Collection.extend({
    url: "/posts.json",
    model: Codetest.Models.Post
});

您需要添加“/”才能正确获取。