【问题标题】:Serve json file from GO server to javascript client将 json 文件从 GO 服务器提供给 javascript 客户端
【发布时间】:2015-07-25 19:50:15
【问题描述】:

我有一个 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']) 那么这不会不行。

【问题讨论】:

  • 请定义 "这不起作用" 。发生什么了?你得到 JavaScript 错误?如果有,你得到了什么?
  • 如果我做console.log(ev.detail.response) 我得到json 作为字符串,但如果我尝试做console.log(ev.detail.response['trial-data']) 我得到了未定义,所以这意味着ev.detail.response 不返回一个数组

标签: javascript arrays json google-app-engine go


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 2020-09-28
    • 2012-07-23
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    相关资源
    最近更新 更多