四种 post 请求格式的XMLHttpRequest 写法

<!DOCTYPE html>
<head>
    <head>
        <meta charset="UTF-8">
        <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"){
            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>
</head>

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

猜你喜欢

转载自blog.csdn.net/harryhare/article/details/80778066