好好爱自己!

【转】四种 post 请求格式的XMLHttpRequest 写法

原文:https://blog.csdn.net/harryhare/article/details/80778066

--------------------------------

前端 js 请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post test</title>>
<script>
function send(type) {
url = "http://127.0.0.1:8080/";
xhr = new XMLHttpRequest();
xhr.open("post", url, true);
var data;
if (type === "formdata") {
data = new FormData();
data.append("key", "value");
} else if (type === "json") {
xhr.setRequestHeader("Content-Type", "application/json");
data = JSON.stringify({"key": "value"});
} else if (type === "text") {
data = "key=value";
} else if (type === "www") {
// 这个header 其实是 传统post 表单的格式
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
data = "key=value";
}
xhr.send(data);
}

</script>
</head>
<body>
<div>
<input type="button" onclick="send('formdata')" value="FormData"/>
<br/>
<input type="button" onclick="send('json')" value="application/json"/>
<br/>
<input type="button" onclick="send('text')" value="text"/>
<br/>
<input type="button" onclick="send('www')" value="application/x-www-form-urlencoded"/>
</div>
</body>
</html>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
后端处理
package main

import (
"fmt"
"net/http"
)


func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("before parse:")
printKey(r);

r.ParseForm()

fmt.Println("ParseForm:")
printKey(r);

r.ParseMultipartForm(2048)

fmt.Println("ParseMultipartForm:")
printKey(r);
}
func printKey( r *http.Request){
fmt.Println(r.Form["key"])
fmt.Println(r.PostForm["key"])
if r.MultipartForm!=nil {
fmt.Println(r.MultipartForm.Value["key"])
}
}

 

func main() {
fmt.Println("listening 8080")
http.HandleFunc("/", IndexHandler)
http.ListenAndServe(":8080", nil)
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
get
http://localhost:8080/?key=value1
before parse:
[]
[]
ParseForm:
[value1]
[]
ParseMultipartForm:
[value1]
[]

1
2
3
4
5
6
7
8
9
10
application/x-www-form-urlencoded:
before parse:
[]
[]
ParseForm:
[value]
[value]
ParseMultipartForm:
[value]
[value]
1
2
3
4
5
6
7
8
9
FormData(MultipartForm)
before parse:
[]
[]
ParseForm:
[]
[]
ParseMultipartForm:
[value]
[value]
[value]

1
2
3
4
5
6
7
8
9
10
11
综上,使用 go 时:
ParseMultipartForm 这个函数要单独调用
postform 中有的 form中一定有,MultipartForm 中有的 postform 和 form也一定有

参考:
四种格式:
https://blog.csdn.net/tTU1EvLDeLFq5btqiK/article/details/78734023
转码说明:
https://www.w3schools.com/tags/att_form_enctype.asp
————————————————
版权声明:本文为CSDN博主「harryhare」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/harryhare/java/article/details/80778066

posted @ 2020-06-11 23:14  立志做一个好的程序员  阅读(2757)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处