index.html 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>form 表单页面</title>
  6. </head>
  7. <body>
  8. <!-- 创建一个表单,提交到本地服务器的 /post/index 路径 -->
  9. <form id="myForm" action="http://localhost:3000/post/index" method="post" style="width: 245px;">
  10. <div>
  11. <label>用户名:
  12. <input type="text" name="iptuname" id="uname" /> <!-- 用户名输入框 -->
  13. </label>
  14. </div><br/>
  15. <div>
  16. <label>密码:
  17. <input type="password" name="iptpwd" id="pwd" /> <!-- 密码输入框 -->
  18. </label>
  19. </div><br/>
  20. <button type="button" id="btn">检测用户是否存在</button><br/> <!-- 检测用户存在的按钮 -->
  21. <input type="submit" value="发送 POST 请求" /><br/> <!-- 提交表单的按钮 -->
  22. </form>
  23. <script>
  24. window.onload = function () {
  25. // 禁用表单的默认提交行为
  26. document.getElementById('myForm').onsubmit = function () {
  27. return false; // 返回 false,阻止表单提交
  28. }
  29. // 监听“检测用户是否存在”按钮的点击事件
  30. document.getElementById('btn').addEventListener("click", function () {
  31. var xhr = new XMLHttpRequest(); // 创建 XMLHttpRequest 对象
  32. xhr.open("POST", "http://localhost:3000/post", true); // 设定请求类型和 URL
  33. // 设置请求头,指定发送的数据类型为 JSON
  34. xhr.setRequestHeader("Content-Type", "application/json");
  35. // 获取输入框的值
  36. var uname = document.getElementById('uname').value; // 获取用户名
  37. var pwd = document.getElementById('pwd').value; // 获取密码
  38. // 构建请求体,将数据转换为 JSON 字符串
  39. var data = JSON.stringify({
  40. iptuname: uname, // 用户名字段
  41. iptpwd: pwd // 密码字段
  42. });
  43. // 发送请求
  44. xhr.send(data);
  45. // 监听请求状态变化
  46. xhr.onreadystatechange = function () {
  47. if (xhr.readyState === 4) { // 请求完成
  48. if (xhr.status === 200) { // 请求成功
  49. var obj = JSON.parse(xhr.responseText); // 解析返回的 JSON 数据
  50. console.log("响应数据: ", obj); // 在控制台输出响应数据
  51. alert("返回的用户名: " + obj.uname); // 弹出返回的用户名
  52. } else {
  53. console.log("请求失败: " + xhr.status); // 记录请求失败的状态
  54. }
  55. }
  56. }
  57. });
  58. }
  59. </script>
  60. </body>
  61. </html>