doushantun0614 2015-05-14 09:00
浏览 32
已采纳

将json文件从GO服务器提供给javascript客户端

I have a go server which has to respond to a javascript request by serving a json file. The json file is an array of objects.

My code :

Server side

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")
}

Client side

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,
      }
    }
  ]
}

If I do that I get the JSON object in JavaScript, but if I try to look into the JSON to get the array- i.e. console.log(ev.detail.response['trial-data']) then this doesn't work.

  • 写回答

1条回答 默认 最新

  • doucanrui1735 2015-05-14 09:26
    关注

    ev.detail.response is just a string response, it is not a parsed json object.

    First you need to parse it using JSON.parse() and then you can access its content.

    See this Javascript example:

    var json = '{"trial-data":[{"trial":{"index": 0}},{"trial":{"index":1}}]}'
    
    alert(JSON.parse(json)['trial-data'])
    

    To access the value of the first "index" field, for example:

    var idx0 = JSON.parse(json)['trial-data'][0]['trial']['index']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)