欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

异步传输实现计算器

程序员文章站 2022-03-07 19:52:06
...
  • 表单页面文件calculator.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>异步计数器</title>
  8. <style>
  9. form input {
  10. width: 80px;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <form id="cal" action="calculate.php" onsubmit="return false">
  16. <input type="number" name="num1" />
  17. <select name="opt" id="">
  18. <option value="1">+</option>
  19. <option value="2">-</option>
  20. <option value="3">*</option>
  21. <option value="4">/</option>
  22. <option value="5">%</option>
  23. </select>
  24. <input type="number" name="num2" />
  25. = <span>?</span>
  26. <button>计算</button>
  27. </form>
  28. <script>
  29. const btn = document.querySelector("button");
  30. btn.addEventListener("click", calClick);
  31. async function calClick() {
  32. const num1 = document.forms.cal.num1.value;
  33. const num2 = document.forms.cal.num2.value;
  34. const opt = document.forms.cal.opt.value;
  35. const response = await fetch(
  36. "calculate.php?num1=" + num1 + "&opt=" + opt + "&num2=" + num2
  37. );
  38. const comments = await response.json();
  39. const res = document.querySelector("form span");
  40. res.textContent = comments;
  41. }
  42. </script>
  43. </body>
  44. </html>
  • 运算文件calculate.php
  1. <?php
  2. $num1=$_GET['num1'];
  3. $num2=$_GET['num2'];
  4. $opt=$_GET['opt'];
  5. $res=0;
  6. switch($opt){
  7. case "1":
  8. $res = $num1 + $num2;
  9. break;
  10. case "2":
  11. $res = $num1 - $num2;
  12. break;
  13. case "3":
  14. $res = $num1 * $num2;
  15. break;
  16. case "4":
  17. if($num2==0){
  18. $res="除数不能是0";
  19. break;
  20. }
  21. $res = $num1 / $num2;
  22. break;
  23. case "5":
  24. if($num2==0){
  25. $res="除数不能是0";
  26. break;
  27. }
  28. $res = $num1 % $num2;
  29. break;
  30. }
  31. echo json_encode($res);

异步传输实现计算器

异步传输实现计算器