英文:
How do I serve json data to a page in Golang?
问题
这是要翻译的内容:
不是关于编组或解组的问题,而是我需要在与我的 jQuery 结合使用时向我的写入器中写入什么?
现在我在 Go 中有以下代码:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, _ := os.Open("adjs.json")
defer j.Close()
var obj respWords
json.NewDecoder(j).Decode(&obj)
js, _ := json.Marshal(obj)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
这是我的 jQuery 获取 JSON 数据的代码:
<script type="text/javascript">
function randomize() {
scene = {}
$.getJSON('adjs.json', function(scene){
console.log('encoding')
})
console.log(scene)
}
</script>
请注意,我只会返回翻译好的部分,不会回答关于翻译内容的问题。
英文:
It's not a matter of marshal or unmarshal, it's what do I need to write to my writer in combination with my Jquery?
Right now I have this for Go
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, _ := os.Open("adjs.json")
defer j.Close()
var obj respWords
json.NewDecoder(j).Decode(&obj)
js, _ := json.Marshal(obj)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
and this is my jquery getting the json
<script type = "text/javascript">
function randomize() {
scene = {}
$.getJSON('adjs.json', function(scene){
console.log('encoding')
})
console.log(scene)
}
</script>
答案1
得分: 3
你的异步请求不会将数据保存到外部变量中,请在ajax请求的成功函数中处理逻辑。
$.getJSON('adjs.json', function(scene){
console.log(scene);
// 在这里处理场景逻辑
});
英文:
your async request does not save the data to the external variable, do your logic in the success function of your ajax request
$.getJSON('adjs.json', function(scene){
console.log(scene);
//do logic here with scene
});
答案2
得分: 2
你可以按照以下方式提供包含JSON的文件:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, err := os.Open("adjs.json")
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
defer j.Close()
w.Header().Set("Content-Type", "application/json")
io.Copy(w, j)
}
不需要对文件进行解码和编码。
你也可以使用ServeFile
函数:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
http.ServeFile(w, r, "adjs.json")
}
英文:
You can serve a file containing JSON as follows:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, err := os.Open("adjs.json")
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
defer j.Close(0
w.Header().Set("Content-Type", "application/json")
io.Copy(w, f)
}
There's no need to decode and encode the file.
You can also use ServeFile:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
http.ServeFile(w, r, "adjs.json")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论