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

huangapple go评论114阅读模式
英文:

Serve json file from GO server to javascript client

问题

我有一个Go服务器,需要通过提供一个JSON文件来响应JavaScript请求。JSON文件是一个对象数组。

我的代码:

服务器端

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']),那么这不起作用。

英文:

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

得分: 4

ev.detail.response只是一个字符串响应,它不是一个解析后的JSON对象。

首先,你需要使用JSON.parse()来解析它,然后你可以访问它的内容。

看看这个JavaScript示例:

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

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

要访问第一个"index"字段的值,例如:

var idx0 = JSON.parse(json)['trial-data'][0]['trial']['index'];
英文:

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']

huangapple
  • 本文由 发表于 2015年5月14日 17:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/30233217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定