1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 8   <title>POST请求参数传递</title>
 9 </head>
10 
11 <body>
12   <form action="javascript:;">
13     <p><input type="text" id="username"></p>
14     <p><input type="password" id="age"></p>
15     <p><input type="button" id="btn" value="submit"></p>
16   </form>
17 
18   <!-- 
19     请求报文
20       在HTTP请求和响应的过程中传递的数据块就叫 报文, 包括要传送的数据和一些附加信息,这些数据和信息要遵守规定好的格式;
21       报文:1.报文头;2.报文体
22         报文头存储的一些键值对信息;
23 
24     POST 请求方式
25       setRequestHeader 用于设置请求报文的报文头信息
26       xhr.setRequestHeader('Content-Type', 'application/x-www-form-uerlencoded')
27       xhr.send('name=zhangsan&age=20')
28     
29     请求参数的格式
30       1. application/x-www-form-uerlencoded
31          name=zhangsan&age=20
32 
33       2. application/json
34         {name: 'zhangsan', age: 20, sex: '男'}
35         在请求头中指定Content-Type属性的值是application/json, 告诉服务器端当前请求参数的格式是json
36         JSON.stringify() // 将json对象转换为json字符串
37     
38     注意!!!
39       get 请求是不能提交JSON对象数据格式的,传统网站的表单提交也是不支持json对象数据格式的
40    -->
41   <script>
42     const btn = document.getElementById('btn');
43     const username = document.getElementById('username');
44     const age = document.getElementById('age');
45     btn.addEventListener('click', (ev) => {
46       const xhr = new XMLHttpRequest();
47       const nameValue = username.value;
48       const ageValue = age.value;
49       const params = `username=${nameValue}&age=${ageValue}`;
50 
51       xhr.open('post', 'http://localhost:3000/post')
52       xhr.setRequestHeader('Content-Type', 'application/x-www-form-uerlencoded')
53       // 如果你的参数是以键值对的形式即这个案例,那这个请求头就要用这个格式:application/x-www-form-uerlencoded
54       xhr.send(params)
55       xhr.onload = function () {
56         // 将JSON字符串转换为JSON对象
57         const responseText = JSON.parse(xhr.responseText);
58         // responseText 保存是的服务器响应返回给客户端的数据
59         const str = '<h2>' + responseText.meta.msg + '</h2>';
60         document.body.innerHTML = str;
61         console.log(responseText);
62       }
63     })
64   </script>
65 </body>
66 
67 </html>