2012-03-15 61 views
0

我剛剛開始學習Javascript並試圖在同一個平臺上構建應用程序......我認爲這是學習的好方法。我正在使用「JavaScript Web Applications」這本書Alex MacCaw來幫助我。Json未完成輸出

我被困在部分地方,我打算將一些字符串序列化爲Json。結果應該是這樣的:

{"7B2A9E8D...":"{"name":"document","picture":"pictures.jpg","id":"7B2A9E8D..."}"} 

但是,這只是爲了測試目的,但它只輸出id記錄,而忽略其餘部分。

這裏是鏈接到我的代碼:

https://gist.github.com/2047336

任何幫助將不勝感激。

回答

0

把它像這樣:

{"7B2A9E8D...":{"name":"document","picture":"pictures.jpg","id":"7B2A9E8D..."}} 

隨着{}你開始一個對象......如果你把「{}」這是一個字符串...但因爲你裏面有很多雙引號字符串,你有語法錯誤。

UPDATE:

,我的問題是,目前尚不清楚你想達到這樣的龐大的代碼應該只保存對象到數組什麼:)(所以我不知道是什麼部分實際上需要被改變)。如果你想幾個簡單的提示,在這裏,他們是:

你有這樣的和平代碼:

var Event = Model.create(); 
     Event.attributes ['name', 'picture']; 
     var _event = Event.init({name: "document", picture: "images.jpg"}); 
     _event.save(); 
     var json = JSON.stringify(Event.records); 
     document.write(json); 

,你實際上是與一些參數(一些對象)調用的init()......但如果你看看在Model.js的「init」函數中,它不接受任何參數。

init: function(){ 
      var instance = Object.create(this.prototype); 
      instance.parent = this; 
      instance.init.apply(instance, arguments); 
      return instance; 
     }, 

到這一點::所以,你從這個改變你的初始化函數這將是很好

init: function(args){ 
      var instance = Object.create(this.prototype); 
      instance.parent = this; 
      instance.init.apply(instance, arguments); 
      jQuery.extend(instance, args); 
      return instance; 
     }, 

即使在那之後,你JSON.stringify將打印錯誤值(僅_id),因爲它是不能夠序列化存在於JavaScript對象中的循環引用。但你的物業在那裏,可以使用。您可以檢查出從這個改變你的代碼:

var Event = Model.create(); 
     Event.attributes ['name', 'picture']; 
     var _event = Event.init({name: "document", picture: "images.jpg"}); 
     _event.save(); 
     var json = JSON.stringify(Event.records); 
     document.write(json); 

到這一點:

var Event = Model.create(); 
     Event.attributes ['name', 'picture']; 
     var _event = Event.init({name: "document", picture: "images.jpg"}); 
     _event.save(); 

     var json = JSON.stringify(Event.records); 
     document.write(json); 

     for(var k in Event.records) 
      alert(Event.records[k]['picture']); 

它會提醒一個很好的「images.jpg」串對你來說,這意味着你的對象,一起與您的屬性,保存並準備使用(json.stringify只是無法告訴你)。

我希望這有助於你的學習努力。

+0

感謝您的回答vucetica,但這實際上是函數'JSON.stringify()'的輸出。 – JayDesign 2012-03-16 00:03:20

+0

我已經更新了我的答案。 – 2012-03-16 02:41:09

+0

爲了回答你的問題,我想實現的目標,我實際上學習如何使用書中的代碼來構建應用程序......就像顯示一個區域中發生夜間事件的網格一樣簡單......對於現在,我只是測試,玩代碼,看看我能做到這一點。我會在今天晚些時候測試您的解決方案並通知您。再次感謝! – JayDesign 2012-03-16 12:48:01