问题
Following is my folder structure
Sample/
css/
js/
libs/
data/
employees.json
app.js
index.html
app.js
App = Ember.Application.create({
LOG_TRANSITIONS: true
});
App.Router.map(function(){
this.resource("employees");
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: "localapps/EmberProjects/Sample/js/data",
url: "employees.json"
});
App.Employee = DS.Model.extend({
name : DS.attr("string")
});
App.EmployeesRoute = Ember.Route.extend({
model: function() {
return this.store.find("employee");
}
});
employees.json
{
"employees": [
{
"name": "Title 1"
},
{
"name": "Title 2"
}
]
}
But when i try to fetch data from the .json file, ember.js automatically replaces the .json in the url with " ".
Original fetch call:
http://localhost/localapps/EmberProjects/Sample/js/data/employees.json
But ember trying to fetch data from
http://localhost/localapps/EmberProjects/Sample/js/data/employees
So no data is recieved from the adapter.
回答1:
@claptimes solution would probably work, but it copies the original implementation which I think is a bad practice since you'll have to manually keep it up to date to the latest version of ember data:)
Also I noticed you're setting the url
property which has been deprecated for a while (https://github.com/emberjs/data/blob/eeb6162f65513caa19ce18887c3f4d1c2014d80c/TRANSITION.md#host-and-namespace-configuration).
Here is a solution that calls _super
and doesn't override the complete method:
App.ApplicationAdapter = DS.RESTAdapter.extend({
buildURL: function() {
return this._super(...arguments) + '.json';
}
});
回答2:
To add the .json
ending to your requests, you could override the buildURL call in the RESTAdapter
. This should work:
DS.RESTAdapter = DS.Adapter.reopen({
buildURL: function(type, id) {
var url = [],
host = get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
if (id) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
url += ".json";
return url;
}
});
回答3:
I had the same problem, but all answers provided here didn’t work. I think that depends on the further development of Ember.js.
Actually I figured it out how to receive the data with the RESTAdapter. You have to add ?jsonp=?
to the path to your JSON file.
Your adapter should look like this:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: "localapps/EmberProjects/Sample/js/data/employees.json?jsonp=?",
});
来源:https://stackoverflow.com/questions/20883902/how-to-retrieve-models-from-json-file-in-ember-js