sammyjsを使用して外部APIからjsonをロードする方法については不明です。
このコードはうまく機能します:
this.get('#/contact', function(context) {
this.load('somefile.json')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item);
});
});
});
ただし、http 経由でロードされた同じ json は失敗します。
this.get('#/contact', function(context) {
this.load('http://samedomain/api/getdata')
.then(function(items) {
$.each(items, function(i, item) {
context.log(item);
});
});
});
http 経由でロードすると、sammy は json をオブジェクトとして認識しなくなり、データをテキストとして解析するように見えます。
これはドメイン アクセスの問題ではありません。
header('Access-Control-Allow-Origin: *');
また、ローカル ファイルとしてロードされたときに正常に動作するように見えるため、json の形式に問題があるとは思いません。
私の残りのAPIも使用しています:
"Content-Type: application/json;
更新: これをワードプレスで使用し、他の誰かに役立つ場合に備えてここにリストします
(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);