利用ajax+php實現商品價格計算

本文實例為大傢分享瞭商品價格計算的具體代碼,利用ajax和php實現以下頁面

index.php

<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8" />
 <title>商品價格計算</title>
 <style type="text/css">
 table {
  border-collapse: collapse;
 }

 tr {
  text-align: center;
 }

 .a4 {
  text-align: right;

  /* padding-right: 15px; */
 }

 #myDiv {
  color: red;
 }

 input {
  border: 0;
 }
 </style>
</head>

<body>
 <form action="data.php" method="get">
 <table border="1" bordercolor="#00CCCC" cellpadding="20">
  <tr>
  <th>商品名稱</th>
  <th>購買數量(斤)</th>
  <th>商品價格(元/斤)</th>
  </tr>
  <tr>
  <td>香蕉</td>
  <td><input type="text" name="a1" value="0" id="n1" onchange="zongji()" /></td>
  <td>8</td>
  </tr>
  <tr>
  <td>蘋果</td>
  <td><input type="text" name="a2" value="0" id="n2" onchange="zongji()" /></td>
  <td>5</td>
  </tr>
  <tr>
  <td>橘子</td>
  <td><input type="text" name="a3" value="0" id="n3" onchange="zongji()" /></td>
  <td>7</td>
  </tr>
  <tr>
  <td colspan="3" class="a4">商品折扣:<span>0.8</span></td>
  </tr>
  <tr>
  <td colspan="3" class="a4">
   <div id="jiage">打折後購買商品總價格: 元</div>
  </td>
  </tr>
 </table>


 </form>


 <script>
 function zongji() {
  var b1 = document.getElementById("n1").value;
  var b2 = document.getElementById("n2").value;
  var b3 = document.getElementById("n3").value;
  //1.創建對象
  var xmlhttp;
  if (window.XMLHttpRequest) {
  // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
  xmlhttp = new XMLHttpRequest();
  } else {
  // IE6, IE5 瀏覽器執行代碼
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  //2.判斷對象是否準備就緒
  xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   document.getElementById("jiage").innerHTML = xmlhttp.responseText;
  }
  };
  //3.發出請求
  xmlhttp.open(
  "GET",
  "demo.php?c1=" + b1 + "&c2=" + b2 + "&c3=" + b3,
  true
  );
  xmlhttp.send();
 }
 </script>
</body>

</html>

data.php

<p>
 <?php
 $d1 = $_GET["c1"];
 $d2 = $_GET["c2"];
 $d3 = $_GET["c3"];
 $sum = (intval($d1) * 8 + intval($d2) * +intval($d3) * 7) * 0.8;
 // $sum=$a1*7.99+$a2*6.89+$a3*3.99;
 echo "打折後購買商品總價格: $sum 元";
 ?>
</p>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀:

    None Found