php - JavaScript:Backbone.js 填充模型集合

标签 php javascript json collections propel

这是我目前所拥有的:

var Item = Backbone.Model.extend({
    defaults: {
        id: 0,
        pid: 0,
        t: null,
        c: null
    },
    idAttribute: 'RootNode_', // what should this be ???
    url: 'page.php'
});

var ItemList = Backbone.Collection.extend({
    model: Item,
    url: 'page.php',
    parse: function(data) {
        alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
    }
});

var ItemView = Backbone.View.extend({
    initialize: function() {
        this.list = new ItemList();
        this.list.bind('all', this.render, this);
        this.list.fetch();
    },
    render: function() {
        // access this.list ???
    }
});

var view = new ItemView();

当前(预期)json 响应:

{
    "RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
    "RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
    "RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}

这成功地轮询了page.php 并且后端作用于$_SERVER['REQUEST_METHOD'] 并返回所需的信息,但是我不知道为什么收集未填满。

ItemListparse 函数中,它正确地显示了所有输出,但它没有做任何事情。

我在代码中为一些更精确的问题留下了一些评论,但主要问题是为什么集合中没有填充明显接收到的数据

最佳答案

将您的parse 方法修改为:

parse: function(response){
   var parsed = [];
   for(var key in response){
      parsed.push(response[key]);
   }
   return parsed;
}

为了遵循约定,将 ItemView 中的 list 更改为 model。同样在 render() 中:

render: function() {
    var template = _.template("<div>some template</div>");
    this.model.each(function(item){ 
        this.$el.append(template(item.toJSON()));
    }, this);
    return this;
}

关于php - JavaScript:Backbone.js 填充模型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9218394/

相关文章:

javascript - Angular:将通过 API 检索到的 JSON 对象的数组分配给变量

java - "no value for rss",虽然它显然在那里

javascript - AWS Lambda - Nodejs 函数不会返回数据

php - 构建 REST API 代码 Igniter

php - 使用 PHPExcel 设置列宽不起作用

Javascript 类型错误 : undefined is not a function when initializing an instance

Javascript:在函数内调用函数时 window.location.href 不重定向

php - 将 php 对象传递给 $.post()

PHP7 返回类型为 JSON

javascript - 如何使输入字段显示实时标记