12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>form 表单页面</title>
- </head>
- <body>
- <!-- 创建一个表单,提交到本地服务器的 /post/index 路径 -->
- <form id="myForm" action="http://localhost:3000/post/index" method="post" style="width: 245px;">
- <div>
- <label>用户名:
- <input type="text" name="iptuname" id="uname" /> <!-- 用户名输入框 -->
- </label>
- </div><br/>
- <div>
- <label>密码:
- <input type="password" name="iptpwd" id="pwd" /> <!-- 密码输入框 -->
- </label>
- </div><br/>
- <button type="button" id="btn">检测用户是否存在</button><br/> <!-- 检测用户存在的按钮 -->
- <input type="submit" value="发送 POST 请求" /><br/> <!-- 提交表单的按钮 -->
- </form>
- <script>
- window.onload = function () {
- // 禁用表单的默认提交行为
- document.getElementById('myForm').onsubmit = function () {
- return false; // 返回 false,阻止表单提交
- }
- // 监听“检测用户是否存在”按钮的点击事件
- document.getElementById('btn').addEventListener("click", function () {
- var xhr = new XMLHttpRequest(); // 创建 XMLHttpRequest 对象
- xhr.open("POST", "http://localhost:3000/post", true); // 设定请求类型和 URL
- // 设置请求头,指定发送的数据类型为 JSON
- xhr.setRequestHeader("Content-Type", "application/json");
- // 获取输入框的值
- var uname = document.getElementById('uname').value; // 获取用户名
- var pwd = document.getElementById('pwd').value; // 获取密码
- // 构建请求体,将数据转换为 JSON 字符串
- var data = JSON.stringify({
- iptuname: uname, // 用户名字段
- iptpwd: pwd // 密码字段
- });
- // 发送请求
- xhr.send(data);
- // 监听请求状态变化
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) { // 请求完成
- if (xhr.status === 200) { // 请求成功
- var obj = JSON.parse(xhr.responseText); // 解析返回的 JSON 数据
- console.log("响应数据: ", obj); // 在控制台输出响应数据
- alert("返回的用户名: " + obj.uname); // 弹出返回的用户名
- } else {
- console.log("请求失败: " + xhr.status); // 记录请求失败的状态
- }
- }
- }
- });
- }
- </script>
- </body>
- </html>
|