四种 post 请求格式的XMLHttpRequest 写法

前端 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>>

后端处理

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)
}

  • get
    http://localhost:8080/?key=value1
 before parse:
[]
[]
ParseForm:
[value1]
[]
ParseMultipartForm:
[value1]
[]

  • application/x-www-form-urlencoded:
before parse:
[]
[]
ParseForm:
[value]
[value]
ParseMultipartForm:
[value]
[value]
  • FormData(MultipartForm)
before parse:
[]
[]
ParseForm:
[]
[]
ParseMultipartForm:
[value]
[value]
[value]

综上,使用 go 时:
ParseMultipartForm 这个函数要单独调用
postform 中有的 form中一定有,MultipartForm 中有的 postform 和 form也一定有

参考:
四种格式:
https://blog.csdn.net/tTU1EvLDeLFq5btqiK/article/details/78734023
转码说明:
https://www.w3schools.com/tags/att_form_enctype.asp

  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值