英文:
How to read custom ajaxParams in Golang http.Request object
问题
我们有以下的ajaxParams:
var ajaxParams = {
type: 'POST',
url: '/golang_endpoint',
dataType: 'json',
customParam: 'customParam',
success: onResponse,
error: onError,
};
在相关的Golang处理程序中,Golang是否可以读取自定义属性,就像它以*http.Request
对象的形式出现一样?
英文:
We have the following ajaxParams:
var ajaxParams = {
type: 'POST',
url: '/golang_endpoint',
dataType: 'json',
customParam: 'customParam',
success: onResponse,
error: onError,
};
Is it possible for Golang to read the custom attribute as it appears in the form of an *http.Request
object in the associated Golang handler?
答案1
得分: 1
这些参数用于执行AJAX请求,它们并不是实际发送到服务器的内容。你应该将它们作为POST请求的数据传递,如下所示:
var ajaxParams = {
type: 'POST',
url: '/golang_endpoint',
dataType: 'json',
data: {customParam: 'customParam'},
success: onResponse,
error: onError,
};
$.ajax(ajaxParams);
然后,在Go端,你可以按照你想要的方式处理数据,例如:
type MyStruct struct {
CustomParam string `json:"customParam"`
}
func HandlePost(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var ms MyStruct
err := dec.Decode(&ms)
if err != nil {
panic(err)
}
fmt.Println(ms.CustomParam)
}
假设你希望参数是一个字符串。无论如何,你都可以将其转换为你想要的类型。
英文:
Those parameters are used to do the AJAX request, they are not what actually gets to the server. You should pass it as the data of the POST request, as in:
var ajaxParams = {
type: 'POST',
url: '/golang_endpoint',
dataType: 'json',
data: {customParam: 'customParam'},
success: onResponse,
error: onError,
};
$.ajax(ajaxParams);
Then, on the Go side, you just handle the data as you want it, like in:
type MyStruct {
customParam string `json:"customParam"`
}
func HandlePost(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var ms MyStruct
err := dec.Decode(&ms)
if err != nil {
panic(err)
}
fmt.Println(ms.customParam)
}
Assuming you want your param to be a string. Either way you could convert it to the type you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论