I’m unclear as to how I am supposed to load json from an external API with sammyjs.
This code works great:
this.get('#/contact', function(context) {
this.load('somefile.json')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item);
});
});
});
However the same json loaded over http fails:
this.get('#/contact', function(context) {
this.load('http://samedomain/api/getdata')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item);
});
});
});
When loading over http, sammy no longer sees the json as objects and appears to parse the data as text.
Just so everyone is clear this is not an issue with domain access.
header('Access-Control-Allow-Origin: *');
Nor do I believe it’s an issue with the format of my json as it appears to work fine when loaded as a local file.
My rest api is also useing:
"Content-Type: application/json;
update:
I put this to use in wordpress and listing it here in the event that it helps someone else
(function($) {
var app = $.sammy('#main', function() {
this.use('Template');
this.helpers({
loadJSON: function(location, options, callback) {
options = $.extend(options, {json: true});
return new Sammy.RenderContext(this).load(location, options, callback);
}
});
this.get('#/', function(context) {
this.loadJSON('http://localhost/wp-somesite/wp-admin/admin-ajax.php?action=get_all_cases')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item);
});
});
});
});
$(function() {
app.run('#/');
});
})(jQuery);
The issue is with to do with how sammy.js determines the type of data it’s retrieving. When you load “mydata.json” the .json tells sammy.js that this is JSON data, however when loading “‘http://samedomain/api/getdata'” it assumes it’s just plain text data.
I don’t know what the best approach would be but two possible solutions are either to change your routing or convert the loaded items to JSON using this.json(…) like so:
Make sure your app has loaded the JSON library with this.use(Sammy.JSON) and that the JSON plugin is loaded in your script definitions.
Edit:
Another option is you can write a custom function that knows to load JSON, here is an example plugin that you could use:
Sammy.JSON.LoadJSON.js:
app.js: