我正在使用Ember,以下代码从api.php脚本获取JSON并在模板上显示结果。我的问题是当我更改getJSON函数以使用.done()而不是.then()时,为什么脚本会中断?我收到以下错误:
:未捕获错误:断言失败:Ember.CollectionView的内容必须实现Ember.Array。你传递了[object Object]。
如果我在函数期间记录了response.items对象,我会在控制台中得到相同的结果,所以我很好奇Ember如何以不同的方式解释它。
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Item.all();
}
});
App.Item = Ember.Object.extend();
App.Item.reopenClass({
all: function() {
return $.getJSON("api.php").then(function(response) {
var items = [];
response.items.forEach( function (item) {
items.push( App.Item.create(item) );
});
return items;
});
}
});
答案 0 :(得分:0)
不确定这是否有帮助,但在我的Ember应用程序中,我使用以下内容来获取一些JSON:
APP.getJSON = function(url) {
return new Ember.RSVP.Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
typeof(this.response) === "string" ? resolve(JSON.parse(this.response)) : resolve(this.response);
} else {
reject(new Error("getJSON: [" + url + "] failed with status: [" + this.status + "]"));
}
}
};
});
}