Go语言数据收发处理及JavaScript JSON编解码问题咨询
数据处理问题解答
1. Go语言中对收发的数据进行操作
在Go语言里处理HTTP请求的收发数据,通常会用到encoding/json包来处理JSON格式的数据,下面是一个完整的示例,包含接收请求、处理数据和返回响应的流程:
package main import ( "encoding/json" "fmt" "net/http" ) // 定义结构体来映射请求的JSON结构,tag对应JSON的键名 type CalculateRequest struct { Operand1 float64 `json:"operand1"` Operand2 float64 `json:"operand2"` Operator string `json:"operator"` } func calculateHandler(w http.ResponseWriter, r *http.Request) { // 只处理POST请求 if r.Method != http.MethodPost { http.Error(w, "仅支持POST请求", http.StatusMethodNotAllowed) return } // 解码请求体中的JSON数据到结构体 var req CalculateRequest err := json.NewDecoder(r.Body).Decode(&req) if err != nil { http.Error(w, "JSON解析失败", http.StatusBadRequest) return } defer r.Body.Close() // 记得关闭请求体 // 这里就是对数据的操作环节,比如根据运算符做计算 var result float64 switch req.Operator { case "+": result = req.Operand1 + req.Operand2 case "-": result = req.Operand1 - req.Operand2 case "*": result = req.Operand1 * req.Operand2 case "/": if req.Operand2 == 0 { http.Error(w, "除数不能为0", http.StatusBadRequest) return } result = req.Operand1 / req.Operand2 default: http.Error(w, "不支持的运算符", http.StatusBadRequest) return } // 构造并发送响应JSON w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]float64{"result": result}) } func main() { http.HandleFunc("/", calculateHandler) fmt.Println("服务器运行在http://localhost:8000") http.ListenAndServe(":8000", nil) }
简单说几个关键步骤:
- 用
json.NewDecoder(r.Body).Decode(&req)把请求体的JSON解析到自定义结构体,方便后续操作 - 对解析后的数据做业务处理(比如示例里的计算)
- 用
json.NewEncoder(w).Encode(...)把处理结果编码成JSON返回给客户端
2. JavaScript中的JSON解码与变量存储
结合你给出的代码片段,我来完善并说明如何实现需求:
把calculate对象的内容保存到op1、op2、opr
这个很直接,直接从对象中取值赋值就行,或者用解构赋值更简洁:
var calculate = { operand1 : null, operand2 : null, operator : null }; // 先给calculate赋值(模拟用户输入) calculate.operand1 = 15; calculate.operand2 = 3; calculate.operator = "/"; // 方式1:直接赋值 const op1 = calculate.operand1; const op2 = calculate.operand2; const opr = calculate.operator; // 方式2:解构赋值(更简洁) const { operand1: op1, operand2: op2, operator: opr } = calculate;
发送请求并解码服务器响应到result
注意:发送JSON数据时,必须用JSON.stringify()把对象转成JSON字符串,否则服务器无法正确解析。然后通过onload事件监听响应,用JSON.parse()解码返回的JSON:
function UserAction() { var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://localhost:8000/", true); xhttp.setRequestHeader("Content-type", "application/json"); // 把calculate对象转成JSON字符串发送 xhttp.send(JSON.stringify(calculate)); // 监听响应完成事件 xhttp.onload = function() { // 检查请求是否成功 if (this.status >= 200 && this.status < 300) { // 解码服务器返回的JSON,取出result值 const responseData = JSON.parse(this.responseText); const result = responseData.result; console.log("计算结果:", result); // 这里可以用result做后续操作,比如渲染到页面 } else { console.error("请求出错:", this.statusText); } }; // 处理网络错误 xhttp.onerror = function() { console.error("网络请求失败,请检查服务器是否运行"); }; }
关键要点:
JSON.stringify():把JavaScript对象序列化为JSON字符串,符合请求头application/json的要求xhttp.onload:必须在这个回调里处理响应,因为XMLHttpRequest是异步的JSON.parse():把服务器返回的JSON字符串解析为JavaScript对象,然后就能取出result字段了
内容的提问来源于stack exchange,提问作者akash sc
相关产品推荐
相关产品推荐

