2015-05-14 113 views
4

我有一個go服務器,它必須通過提供json文件來響應javascript請求。 json文件是一個對象數組。服務json文件從GO服務器到JavaScript客戶端

我的代碼:

服務器端

package expt 

import (
    "net/http" 
) 


func init() { 
    http.HandleFunc("/", handleStatic) 
    http.HandleFunc("/loadTrials", handleloadJson) 
} 

func handleStatic(w http.ResponseWriter, r *http.Request) { 
    w.Header().Set("Cache-Control", "no-cache") 
    http.ServeFile(w, r, "static/"+r.URL.Path) 
} 


func handleloadJson(w http.ResponseWriter, r *http.Request) { 
    http.ServeFile(w, r, "static/trial.json") 
} 

客戶端

loadTrials : function loadTrials() { 

      var _this = this, 
       load = this.shadowRoot.querySelector('#load-trial'); 

      load.url="http://url:8080/loadTrials"; 
      load.go() 
      load.addEventListener('core-response', function(ev) { 
       console.log(ev.detail.response) 
      }, false); 
     } 

的Json

{ 
    "trial-data" : [ 
    { 
     "trial" : { 
     "index": 0, 
     } 
    }, 
    { 
     "trial" : { 
     "index": 1, 
     } 
    } 
    ] 
} 

如果我這樣做,我得到了JavaScript中的JSON對象,但如果我試圖查看JSON獲取數組,即console.log(ev.detail.response ['trial-data']),那麼這不起作用。

+4

請定義_ 「這行不通」 _。怎麼了?你得到JavaScript錯誤?如果是這樣,你得到了什麼? – icza

+0

如果我做'console.log(ev.detail.response)'我得到json作爲字符串,但如果我嘗試做'console.log(ev.detail.response ['trial-data'])'我得到了undefined ,所以這意味着'ev.detail.response'不會返回一個數組 – Dede

回答

3

ev.detail.response只是一個字符串響應,它不是一個解析的json對象。

首先,您需要使用JSON.parse()解析它,然後才能訪問其內容。

看到這個JavaScript示例:

var json = '{"trial-data":[{"trial":{"index": 0}},{"trial":{"index":1}}]}' 

alert(JSON.parse(json)['trial-data']) 

訪問Value第一"index"領域,例如:

var idx0 = JSON.parse(json)['trial-data'][0]['trial']['index'] 
相關問題