英文:
unable to access post request params in golang
问题
我正在尝试在Golang中访问通过jQuery Ajax发送的post参数。也许我漏掉了一些明显的东西。以下是我的代码片段:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$('form').submit(function(e) {
e.preventDefault();
var jsn = {
vvv: $("#textinput").val()
};
console.log(jsn);
$.ajax({
type: "POST",
async: true,
url: "/homepage",
data: jsn,
processData: true,
contentType: "application/json",
cache: false,
}).done(function(response){
$("#resultdiv").html(response);
});
});
</script>
</head>
</html>
这是我的Golang代码:
func MainConversion(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := r.FormValue("vvv")
fmt.Fprint(w, string(text))
return
}
我尝试过f.formValue()
和r.Form.Get()
。提前感谢您的帮助。
英文:
I am trying to access post params in golang which are sent via jquery ajax. Maybe I am missing something obvious. Here are my code snippets
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$('form').submit(function(e) {
e.preventDefault();
var jsn = {
vvv = $("#textinput").val();
};
console.log(jsn);
$.ajax({
type: "POST",
async : true,
//enctype: 'multipart/form-data',
url: "/homepage",
data: jsn,
processData: true,
contentType: "application/json",
cache: false,
}).done(function(response){
$("#resultdiv").html(response);
});
});
</script>
here is my golang code:
func MainConversion(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := r.FormValue("vvv")
fmt.Fprint(w, string(text))
return
})
I have tried f.formValue(), r.Form.get() . Thanks in advance
答案1
得分: 3
你已经发送了一个带有JSON主体的请求,但是ParseForm
在*http.Request
上不能处理JSON。你需要读取请求的主体并将其解析为JSON,或者不要将主体发送为JSON。
func MainConversion(w http.ResponseWriter, r *http.Request) {
var body = make(map[string]string)
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
text := body["vvv"]
w.Write([]byte(text))
}
英文:
You've sent your request with a JSON body, but ParseForm
on an *http.Request
does not handle JSON. You need to read the body of the request and parse it as JSON, or don't send your body as JSON.
func MainConversion(w http.ResponseWriter, r *http.Request) {
var body = make(map[string]string)
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
text := body["vvv"]
w.Write([]byte(text))
}
答案2
得分: 0
你的JS代码片段存在语法错误,所以我假设没有请求到达你的Golang API。
应该修改为:
var jsn = {
vvv: $("#textinput").val()
};
英文:
Your JS snippet contains syntax errors, so I assume no request reaches your golang API.
var jsn = {
vvv = $("#textinput").val();
};
should be:
var jsn = {
vvv : $("#textinput").val()
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论