我最近开始学习Ember,现在我正在尝试了解如何使用Ember Data对数据进行ajax调用。当我导航到页面'路由时,我想获取数据并将响应记录到控制台。
这是我的代码,但无法记录数据:
Handlebars和JS:
<script type="text/x-handlebars">
<nav>
{{#link-to 'home'}}Home{{/link-to}}
{{#link-to 'pages'}}Pages{{/link-to}}
</nav>
<div class="container">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" id="pages">
Info here
{{log}}
</script>
App = Ember.Application.create();
App.Router.map(function() {
this.route('home', {path: '/'});
this.route('home', {path: 'home'});
this.route('pages', {path: 'pages'});
});
App.Pages = DS.Model.extend({
status: DS.attr('string'),
startDate: DS.attr('string'),
lastModifiedDate: DS.attr('string'),
author: DS.attr('string'),
lastModifiedBy: DS.attr('string'),
title: DS.attr('string'),
items: {}
});
App.PagesAdapter = App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://api.mongolab.com/api/1/databases/emberdatatest/collections/itemdata?apiKey=somekey'
});
App.PagesRoute = Ember.Route.extend({
model: function() {
this.store.find('pages');
}
});
以下是我回复的数据:
{
"_id": {
"$oid": "5460cc6be4b0933065794003"
},
"start": 0,
"count": 5,
"total": 1549,
"pages": [
{
"status": "published",
"startDate": "2014-09-24 12:56",
"lastModifiedDate": "2014-10-02 12:01",
"author": "Luke Skywalker",
"lastModifiedBy": "Darth Vader",
"title": "home page",
"items": {}
},
{
"status": "published",
"startDate": "2014-10-13 08:03",
"lastModifiedDate": "2014-10-02 12:01",
"author": "Sauran",
"lastModifiedBy": "Gandolf",
"title": "Blog page",
"items": {}
},
{
"status": "review",
"startDate": "2014-11-22 13:03",
"lastModifiedDate": "2014-11-14 14:01",
"author": "Jean-Luc Piccard",
"lastModifiedBy": "Worf",
"title": "Vacuum Cleaners page",
"items": {}
}
]
}
答案 0 :(得分:1)
而不是
this.store.find('pages');
你应该致电
this.store.find('page');
它将向
提出请求https://api.mongolab.com/api/1/databases/emberdatatest/collections/itemdata?apiKey=somekey的 /网页
然后api应该以下列格式给你回复(如果使用Rest适配器)
"posts": [{
"id": 1,
"status": "foo",
"startDate": "foo",
"lastModifiedDate": "foo",
"author": "foo",
"lastModifiedBy": "foo",
"title": "foo"
}]
在路由器model
方法中,您应该从匿名函数
App.PagesRoute = Ember.Route.extend({
model: function() {
return this.store.find('pages');
}
});
然后你可以检查ember inspector
一切是否正常。
如果你不能强制你的api返回预期的格式,你就可以在不使用数据的情况下执行此操作
App.PagesRoute = Ember.Route.extend({
model: function() {
return jQuery.getJSON('https://api.mongolab.com/api/1/databases/emberdatatest/collections/itemdata?apiKey=somekey/', function(json) {
return json
});
}
});
如果您想使用余烬数据,我建议您查看:
http://emberjs.com/guides/models/finding-records/
http://emberjs.com/guides/models/connecting-to-an-http-server/