You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Golang的*http.Request对象中读取自定义ajaxParams参数

能否在Golang处理器中读取AJAX请求的自定义参数?

答案是不能直接通过*http.Request读取你定义的customParam,具体原因和解决办法如下:

  • 你在ajaxParams里添加的customParam只是AJAX库(比如jQuery)的本地配置项,并不会被打包发送到服务器端。这类库只会遵循HTTP协议规范,用type、url、dataType这类标准字段构造实际请求,自定义属性不会出现在请求报文里。
  • 如果要让Golang处理器获取到这个参数,你需要把customParam放到data字段中,修改后的ajaxParams如下:
var ajaxParams = {
    type: 'POST',
    url: '/golang_endpoint',
    dataType: 'json',
    data: {
        customParam: 'customParam'
    },
    success: onResponse,
    error: onError,
};
  • 之后在Golang处理器中,就可以通过解析请求体(因为是POST+JSON格式)来获取该参数:
import (
    "encoding/json"
    "net/http"
)

type RequestData struct {
    CustomParam string `json:"customParam"`
}

func handler(w http.ResponseWriter, r *http.Request) {
    var data RequestData
    err := json.NewDecoder(r.Body).Decode(&data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    // 此处可直接使用data.CustomParam
}

内容的提问来源于stack exchange,提问作者Peabrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 01:35:45