
我有 html:
<button onclick="clicklistener()" id="form-button" type="button" class="btn btn-primary">click</button>
js:
<script>
const clicklistener = () => {
console.log('clicklistener()')
fetch("/address")
.then(response => {
console.log(response)
})
.catch(e => {
console.log(e)
})
}
</script>去:
func Handler(writer http.ResponseWriter, request *http.Request) {
response := jsonResponse{IsAvailable: true, Message: "Available"}
responseInJsonFormat, err := json.MarshalIndent(response, "", " ")
if err != nil {
log.Println("cannot convert response data to JSON")
return
}
writer.Header().Set("Content-Type", "application/json")
_, err = writer.Write(responseInJsonFormat)
if err != nil {
log.Println("cannot convert response data to JSON")
}
}如果我使用浏览器,我会收到 json 格式的响应,其中包含数据 {isavailable: true, message: "available"}。
立即学习“go语言免费学习笔记(深入)”;
一切正常。
但由于某种原因我无法在 js 中获取这些数据。 我在 js 中得到的响应是:
没有标题或数据。
我怎样才能得到它?
谢谢!
fetch 返回一个 response 对象,然后必须将其解析为可用的格式,例如 json 或文本。由于您想要 json 格式,因此需要执行以下操作:
fetch('/address')
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log(e))以上就是无法从 Golang 服务器获取 JS 响应的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号