【轉】四種 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM