0

我有一个backbone.js 错误:

未捕获的类型错误:无法使用 'in' 运算符在 {"websiteID":"2","title":"titre site 2"} 主干-min.js:9 中搜索 'id'

我正在尝试将 json 数据(从 ajax 接收)复制到模型的实例中。

我该如何解决这个问题?

我的代码是:

var Website = Backbone.Model.extend({
    // set default json data in the website:
    defaults: {"websiteID":"1","title":"default title"}
});

var website = new Website();

function UpdateWebsiteBasedOnDBData() {
  this.url = 'script.php';
}

UpdateWebsiteBasedOnDBData.prototype.readData = function(dataToGet) {
        return $.ajax({
        type: "GET",
        url: this.url,
        data: dataToGet,
        context: this,
        success: this.onSuccess
      });
};

UpdateWebsiteBasedOnDBData.prototype.onSuccess = function(data) {
    website.set(data);
    alert( website.get("websiteID") );
};

$(document).ready(function() {
    var updateWebsiteBasedOnDBData = new UpdateWebsiteBasedOnDBData();
    updateWebsiteBasedOnDBData.readData({"websiteID": 2});
});

script.php 返回正确的 json:

{"websiteID":"2","title":"网站名称 2"}


更新

我仍然需要检查,但我强烈怀疑我的 json 实际上是无效的。根本原因可能是(仍有待验证)我的 php 脚本的字符集。

相关:json 内容类型开头的奇怪字符

4

1 回答 1

0

我只是猜测您必须为模型命名身份字段。

http://documentcloud.github.com/backbone/#Model-idAttribute

但是我不太确定您发布的代码是否存在问题。我过去使用过没有 id 的模型,IIRC,对于某些模型,我只想实现只读视图/搜索功能,而不是 CRUD 功能,并且身份在这些场景中并不重要......(这是之前但是,Backbone.js 的当前版本,我可能完全不在乎这个......)

于 2012-09-03T17:09:32.020 回答