2012-07-27 35 views
2

加載JSON我不清楚的,我應該如何從sammyjs外部API加載JSON。SammyJS從http

此代碼的偉大工程:

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,薩米不再看到JSON作爲對象,似乎解析數據爲文本。

只是讓每個人都清楚這是不是與域訪問的問題。

header('Access-Control-Allow-Origin: *'); 

我也不相信這是我的json格式的問題,因爲它似乎在加載爲本地文件時工作正常。

我的REST API也期運用:

"Content-Type: application/json; 

更新: 我把這個在WordPress的使用,因爲它可以幫助其他人的事件在這裏上市了

(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的);

回答

2

的問題是與sammy.js如何確定數據的它的檢索式做。當加載「mydata.json的」以.json告訴sammy.js這是JSON數據,但加載時「的‘http://導航特殊/ API /的GetData’」它假定它只是純文本數據。

我不知道最好的方法是什麼,但兩個可能的解決方案是要麼改變你的路由或使用this.json轉換加載項JSON(...),像這樣:

this.get('#/contact', function(context) { 
    this.load('http://samedomain/api/getdata') 
    .then(function(items) { 
     $.each(this.json(items), function(i, item) { 
      context.log(item); 
     }); 
    }); 

}); 

確保您的應用加載了JSON庫this.use(Sammy.JSON),而JSON插件加載腳本定義。

編輯: 另一種選擇是,你可以寫一個知道加載JSON的自定義功能,這裏有一個例子插件,您可以使用:

Sammy.JSON.LoadJSON.js:

(function($) { 
    Sammy.JSON.LoadJSON = function(app) { 
     app.helpers({ 
      loadJSON: function(location, options, callback) { 
       options = $.extend(options, {json: true}); 
       return new Sammy.RenderContext(this).load(location, options, callback); 
      } 
     }); 
    } 
})(jQuery); 

app.js:

this.use(Sammy.JSON.LoadJSON); 

var app = $.sammy('#mytag', function() { 
    this.get('#/contact', function(context) { 
     this.loadJSON('http://samedomain/api/getdata') 
     .then(function(items) { 
      $.each(items, function(i, item) { 
       context.log(item); 
      }); 
     }); 
    }); 
}); 
+0

我給這個一掄。現在它有意義的將它看作文本。我感謝您的幫助! – alloyking 2012-08-02 15:14:45

5

除了什麼VoDurden說,你也可以通過它EXPL加載選項icitly設置dataType。如果你看一下Sammy Load function on Github,你可以看到,它只是一個AJAX調用的包裝。

嘗試這樣:

​​
+0

非常有幫助。謝謝。 – alloyking 2012-08-02 15:13:38

+0

這對我有用! – Maarten 2013-05-12 19:35:11

+1

我認爲這應該是正確的答案。 – emostafa 2016-03-05 14:56:04