Blogger Information
Blog 47
fans 0
comment 3
visits 44850
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
异步传输实现计算器
江流
Original
563 people have browsed it
  • 表单页面文件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);

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:switch中判断能否用更加直观的方式?
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post