透過後端主機以郵件方式傳送訂單
前端將購物車物件一筆一筆抓出來,製作成一張文字型態的訂單(字串),再將此訂單字串傳至後端,做為郵件的內文。在後端PHP中,使用mail方法傳送信件給訂單收件郵箱,在虛擬主機方面,可以進後台,使用Web郵件檢視訂單。
訂購人:陳富國
項目1:招牌酥炸雞腿飯 單價:95元, 數量:1 小計:95元
項目2:泰式椒麻雞腿飯 單價:90元, 數量:1 小計:90元
項目3:日式蜜汁雞腿飯 單價:90元, 數量:1 小計:90元
訂單總金額: 275元
<script> function submit_order(){ var orderBody = ""; var cartItems = shoppingCart.listCart(); //傳回購物車項目的陣列 var orderTotal = 0; //訂單總金額 for (var i = 0; i < cartItems.length; i++){ var cartItem = cartItems[i]; //cartItem是一個JSON物件 // console.log(cartItemArray); orderBody += '項目' + (i+1) + ':' + cartItem['name'] + ' 單價:' + cartItem['price'] + '元,' + ' 數量:' + cartItem['count'] + ' 小計:' + parseFloat( cartItem['total'] ) + '元' + '<br>'; orderTotal = orderTotal + parseFloat( cartItem['total'] ); } //console.log("訂單總金額: " + orderTotal + "元" ) orderBody += "訂單總金額: " + orderTotal + "元" + "<br>"; console.log(orderBody); $.ajax({ //使用jQuery的ajax方法進行POST資料到後端 url: 'index.php', type: 'POST', data: { 'order': orderBody }, success: function (result) { alert('訂單發送成功'); }, error: function(jqxhr, status, exception) { alert('Exception:', exception); } }); } </script> <?php if ( isset($_POST["order"]) ) { $orderBody = stripslashes($_POST["order"]); $to ="wda2216@wda2216.stu.fgchen.com"; //收件者 $subject = "新便當訂單"; //信件標題 $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: wda2216<wda2216@wda2216.stu.fgchen.com>'; if(mail($to, $subject, $orderBody, $headers)) echo "信件發送成功";//寄信成功就會顯示的提示訊息 else echo "信件發送失敗!";//寄信失敗顯示的錯誤訊息 } ?>
stripslashes這個函式的功用是去掉字串的"",主因是從前端傳送字串資料時,有的平台會在字串中加入逸出字元。
其中$.ajax( ... ) 這個方法要送入一個JSON物件:
{ url: 'index.php', type: 'POST', data: { 'order': orderBody }, success: function (result) { alert('訂單發送成功'); }, error: function(jqxhr, status, exception) { alert('Exception:', exception); } }
json物件是由1~多個的key:value組合成(逗點隔開),從上面的例子不難理解每組key:value的用途,url是指定POST資料要發往的目標檔案,此例是index.php(本身),type是指定傳送的型態,計有POST、GET等,通常,我們使用POST,data即是從ajax前端要發往後端的JSON物件,同樣的,這個data物件也是可以由1~多筆的key:value組成,success是指資料從前端傳到後端成功之後,指定回呼函式(callback),我們可以將成功傳送後所要撰寫的程式放在這個方法中,若發生錯誤則由error指定的callback方法執行相關的錯誤處理程序。
信件成功送出後,我們要清空購物車,然後把購物車的對話方塊關閉:
$(".clear-cart").click(); //觸發"清除購物車按鈕" $("#cart").modal('hide'); //隱藏購物車對話方塊
底下的教學是在前端把購物車物件字串化(序列化)後傳到後端PHP,PHP再將含有購物車資料的字串解析出來,比較複雜,不建議使用。
要將JSON物件資料傳到PHP必須先將物件字串化:
var cartString = JSON.stringify(cartObject);
在便當訂單這邊,購物車物件cartObject印出來是:
(4) [{…}, {…}, {…}, {…}] 0: {name: "招牌酥炸雞腿飯", price: 90, count: 1, total: "90.00"} 1: {name: "泰式椒麻雞腿飯", price: 90, count: 2, total: "180.00"} 2: {name: "日式蜜汁雞腿飯", price: 95, count: 2, total: "190.00"} 3: {name: "招牌牛肉麵", price: 110, count: 1, total: "110.00"} length: 4 __proto__: Array(0)
cartString是cartObject字串化的結果:
[{"name":"招牌酥炸雞腿飯","price":90,"count":1,"total":"90.00"},{"name":"泰式椒麻雞腿飯","price":90,"count":2,"total":"180.00"},{"name":"日式蜜汁雞腿飯","price":95,"count":2,"total":"190.00"},{"name":"招牌牛肉麵","price":110,"count":1,"total":"110.00"}]
我們來寫一個GET方式取得資料的PHP了解一下,我們要如何處理資料。
jsonObjectArray.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <?php // JSON string $cartData = stripslashes(($_GET["cartData"]); // Convert JSON string to Array $cartArray = json_decode($cartData, true); print_r($cartArray); // Dump all data of the Array // echo $someArray[0]["name"]; // Access Array data // Convert JSON string to Object $cartObject = json_decode($cartData); print_r($cartObject); // Dump all data of the Object // echo $someObject[0]->name; // Access Object data ?>
在瀏覽器網址列下:
http://localhost/DingBianDong-c-p/jsonObjectArrary.php?cartData=[{"name":"招牌酥炸雞腿飯","price":90,"count":1,"total":"90.00"},{"name":"泰式椒麻雞腿飯","price":90,"count":2,"total":"180.00"},{"name":"日式蜜汁雞腿飯","price":95,"count":2,"total":"190.00"},{"name":"招牌牛肉麵","price":110,"count":1,"total":"110.00"}]
原始的網頁顯示為:
Array ( [0] => Array ( [name] => 招牌酥炸雞腿飯 [price] => 90 [count] => 1 [total] => 90.00 ) [1] => Array ( [name] => 泰式椒麻雞腿飯 [price] => 90 [count] => 2 [total] => 180.00 ) [2] => Array ( [name] => 日式蜜汁雞腿飯 [price] => 95 [count] => 2 [total] => 190.00 ) [3] => Array ( [name] => 招牌牛肉麵 [price] => 110 [count] => 1 [total] => 110.00 ) ) Array ( [0] => stdClass Object ( [name] => 招牌酥炸雞腿飯 [price] => 90 [count] => 1 [total] => 90.00 ) [1] => stdClass Object ( [name] => 泰式椒麻雞腿飯 [price] => 90 [count] => 2 [total] => 180.00 ) [2] => stdClass Object ( [name] => 日式蜜汁雞腿飯 [price] => 95 [count] => 2 [total] => 190.00 ) [3] => stdClass Object ( [name] => 招牌牛肉麵 [price] => 110 [count] => 1 [total] => 110.00 ) )
透過"檢視網頁原始碼",可以將上面的結果以展開的方式來檢視:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> Array ( [0] => Array ( [name] => 招牌酥炸雞腿飯 [price] => 90 [count] => 1 [total] => 90.00 ) [1] => Array ( [name] => 泰式椒麻雞腿飯 [price] => 90 [count] => 2 [total] => 180.00 ) [2] => Array ( [name] => 日式蜜汁雞腿飯 [price] => 95 [count] => 2 [total] => 190.00 ) [3] => Array ( [name] => 招牌牛肉麵 [price] => 110 [count] => 1 [total] => 110.00 ) ) Array ( [0] => stdClass Object ( [name] => 招牌酥炸雞腿飯 [price] => 90 [count] => 1 [total] => 90.00 ) [1] => stdClass Object ( [name] => 泰式椒麻雞腿飯 [price] => 90 [count] => 2 [total] => 180.00 ) [2] => stdClass Object ( [name] => 日式蜜汁雞腿飯 [price] => 95 [count] => 2 [total] => 190.00 ) [3] => stdClass Object ( [name] => 招牌牛肉麵 [price] => 110 [count] => 1 [total] => 110.00 ) )
由以上的方式,我們可以知道我們可以將購物車的字串化資料傳遞給PHP。
新的jsonObjectArray.php + 後端發信
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <?php // JSON string if (isset($_GET["cartData"])) $cartData = stripslashes($_GET["cartData"]); if (isset($_GET["orderPeople"])) $orderPeople = stripslashes($_GET["orderPeople"]); // Convert JSON string to Array $cartArray = json_decode($cartData, true); // print_r($cartArray); // Dump all data of the Array // echo $cartArray[0]["name"]; // Access Array data // Convert JSON string to Object // $cartObject = json_decode($cartData); // print_r($cartObject); // Dump all data of the Object // echo $cartObject[0]->name; // Access Object data $orderStr = '訂購人:'.$orderPeople.'rn'; $orderMoney = 0; // echo count($cartArray) + "<BR>"; for ($i=0; $i < count($cartArray); $i++){ $orderStr .= "第".($i+1)."筆餐點:".$cartArray[$i]["name"]. ",數量=".$cartArray[$i]["count"]. ",單價=".$cartArray[$i]["price"]. ",小計=".$cartArray[$i]["total"].'rn; $orderMoney += intval($cartArray[$i]["total"]); } $orderStr .= "本筆訂單應收金額為".$orderMoney.''rn'; $to ="fgchen@gmail.com "; //收件者 $subject = "新便當訂單"; //信件標題 $msg = $orderStr; $headers = "From: wda1902@wda1902.stu.fgchen.com'"; //寄件者 if(mail("$to", "$subject", "$msg", "$headers")): echo "信件發送成功。";//寄信成功就會顯示的提示訊息 else: echo "信件發送失敗!";//寄信失敗顯示的錯誤訊息 endif; ?>
測試url:
https://wda1902.stu.fgchen.com/DingBianDong-c-p/jsonObjectArrary.php?orderPeople=陳富國&cartData=[{"name":"招牌酥炸雞腿飯","price":90,"count":1,"total":"90.00"},{"name":"泰式椒麻雞腿飯","price":90,"count":2,"total":"180.00"},{"name":"日式蜜汁雞腿飯","price":95,"count":2,"total":"190.00"},{"name":"招牌牛肉麵","price":110,"count":1,"total":"110.00"}]
練習測試結束後,我們正式改寫訂餐:
submit_order函式,按下送出訂單所執行的函式:
function submit_order(){ //JSON.stringify將json物件轉換成字串 // console.log( JSON.stringify(shoppingCart.listCart())); //JSON.prse將資料轉換成json物件 // console.log( JSON.parse(JSON.stringify(shoppingCart.listCart()))); var cartObject = shoppingCart.listCart(); //購物車物件,內含所有的點餐項目(餐點名稱、價格、數量、小計) var cartString = JSON.stringify(cartObject); //將jsons物件轉換成字串形式 var request = new XMLHttpRequest(); request.open("POST", "index.php"); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send("orderPeople="+ $('#orderPeople').val()+"&cartData="+cartString); $(".clear-cart").click(); //觸發"清除購物車按鈕" $("#cart").modal('hide'); //隱藏購物車對話方塊 }
PHP段:(可放在</body>之前)
<?php if (isset($_POST["cartData"]) && isset($_POST["orderPeople"])) { $cartData = stripslashes($_POST["cartData"]); $orderPeople = stripslashes($_POST["orderPeople"]); // Convert JSON string to Array $cartArray = json_decode($cartData, true); $orderStr = '訂購人:'.$orderPeople."rn"; $orderMoney = 0; //訂單總金額 // echo count($cartArray) + "<BR>"; for ($i=0; $i < count($cartArray); $i++){ $orderStr .= "第".($i+1)."筆餐點:".$cartArray[$i]["name"]. //餐點名悄 ",數量=".$cartArray[$i]["count"]. //數量 ",單價=".$cartArray[$i]["price"]. //單價 ",小計=".$cartArray[$i]["total"]."rn"; //小計 $orderMoney += intval($cartArray[$i]["total"]); } $orderStr .= '本筆訂單應收金額為'.$orderMoney."rn"; $to ="fgchen@gmail.com "; //收件者 $subject = "新便當訂單"; //信件標題 $msg = $orderStr; $headers = "MIME-Version: 1.0" . "rn"; // $headers .= "Content-type:text/html;charset=UTF-8" . "rn"; $headers .= 'From: wda1902<wda1902@wda1902.stu.fgchen.com>' . "rn"; if(mail($to, $subject, $msg, $headers)): echo "信件發送成功。";//寄信成功就會顯示的提示訊息 else: echo "信件發送失敗!";//寄信失敗顯示的錯誤訊息 endif; } ?>
送至信箱的訂單郵件:
線上範例:http://wda1902.stu.fgchen.com/DingBianDong-c-p/
參考資料:
Convert and Loop through JSON with PHP and JavaScript Arrays/Objects