无法从服务器 json 响应创建 backbone js 集合

cannot create backbone js collection from server json response

好的。 我知道这里有很多关于这个问题的问题,但我的问题与它有点不同。

我有 laravel 作为后端服务器和定义的路由:

路线::post('/allusers',array('uses'=>'UsersController@index');

@index方法(laravel):

public function index()
{
    //
    $user=DB::table('users')->select('id','name','email')->get();;
    if($user){
        return response()->json($user);
    }
    return "failed";
}

然后,我有一个 backbonejs 集合和模型,如下所示: 用户模型:

user = Backbone.Model.extend({
urlRoot: '/user/'+this.id,
    default:{
        'name':'',
        'email':'unknown@no-name.com',
    },
render:function(){
    console.log(this.name);
}
, initialize:function(){
    console.log('model user created'+this.cid);
    console.log(this.name);
}

});

和backbone合集:

UserCollection = Backbone.Collection.extend({
    model:user,
    url:'/allusers/',
    parse:function(resp,xhr){
             rt= _.toArray(resp);
 return rt;
    },
    initialize:function(){
       this.fetch();
    }
});

但无法创建集合。集合的 models 属性始终为 0。

这是 laravel 的 JSON 回复:

[Object { id=1,  name="abc",  email="someone@google.com"}, Object { id=2,  name="anotheruser",  email="anotheruser@gmail.com"}]

拜托,任何建议。

提前谢谢你。

您没有 return 从您的 laravel 中获取有效的 JSON。 Backbone 假定它是错误的并触发错误 callback.use this snippet to return as JSON.

if($user){
      return Response::json($user->toArray());
    }

使用完美的 json returned,您不必在模型中进行解析。所以你可以从你的模型中删除解析函数(除非你想对数据进行操作)。
所以你的模型应该是这样的,

UserCollection = Backbone.Collection.extend({
    model:user,
    url:'/allusers/',
    initialize:function(){
       this.fetch();
    }
});