【发布时间】:2018-03-17 17:52:53
【问题描述】:
如何解码已在 javascript 中发送到服务器的 json 对象 并将它们保存到变量 op1,op2,opr。
在 java 脚本中,我想解码服务器发送的响应并将其保存为变量结果。
java脚本代码:
var calculate = {
operand1 : null,
operand2 : null,
operator : null
};
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8000/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(calculate);
var response = (xhttp.responseText);
console.log(response);
}
UserAction();
转到服务器代码:
package main
import ("fmt"
"net/http"
"encoding/json"
)
type answer struct {
result float64
}
func index(w http.ResponseWriter, r *http.Request) {
ans := answer{result: 30}
fmt.Println(r)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(ans); err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/",index)
http.ListenAndServe(":8000", nil)
}
【问题讨论】:
-
虽然我回答了您的问题,但考虑到您之前刚刚提出的问题,这是一项非常省力的工作:stackoverflow.com/questions/49338485/… 避免这样做。花点时间阅读文档来熟悉 Go。
-
请注意,您不能对未导出的字段进行编码或解码,例如“结果”。
标签: javascript json go request httpwebresponse