jfp*_*ios 5 javascript api jquery getjson ember.js
我正在使用 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;
});
}
});
Run Code Online (Sandbox Code Playgroud)
不确定这是否有帮助,但在我的 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 + "]"));
}
}
};
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5764 次 |
| 最近记录: |