亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 php mail -ajax 發送購物車詳細信息

通過 php mail -ajax 發送購物車詳細信息

aluckdog 2022-12-22 14:38:34
我在一個 JS 購物車網站上工作,我正在嘗試使用 php 郵件將購物車詳細信息發送到結帳功能中的郵件,這里我通過 ajax 將我的購物車詳細信息傳遞給 php。在 php 中,當嘗試使用 foreach 發送所有購物車值時,我只能接收購物車的最后一行,因為 foreach 正在重新計算先前的值我如何檢索購物車值并以某種格式發送它們jsfunction SendMail() {    var tableContent = localStorage.getItem('productsInCart');    $.post('read.php', {tableContent: tableContent}, function (data) {        console.log(tableContent);    });}PHPif (isset($_POST['tableContent'])) {    $tableContent = json_decode($_POST['tableContent']);    foreach ($tableContent as $tableContent) {        $name = ($tableContent->name);        $price = ($tableContent->price);        $quantity = ($tableContent->inCart);    }    $mailTo = "xxxxxxxxxxxxx";    $Subject = " order details ";    $headers = "from :" . $contact;    $txt = "New registration \n Item:" . $name . "\n Quantity:" . $quantity . "\n Price:" . $price . "\n\n\n CUSTOMER DERAILS\n\n Name:" . $contact . "\n Reg No:" . $reg;    mail($mailTo, $Subject, $txt, $headers);    header("location: read.php?mailsend");}
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

您目前正在循環的每次迭代中覆蓋相同的變量,這就是為什么它們只包含最后一個條目的原因。


您應該改為附加值,執行以下操作:


$tableContent = json_decode($_POST['tableContent']);


// Define a variable to store the items in

$items = '';

// Let's add a total sum as well

$total = 0;


// Let's also use different variable names here

foreach ($tableContent as $item) {        

    // Append to the variable (notice the . before the =)

    $items .= 'Item: ' . $item->name . "\n";

    $items .= 'Quantity: ' . $item->inCart . "\n";

    $items .= 'Price: ' . $item->price . "\n\n";

    

    // Add the price to the total (I'm assuming that the price is an integer)

    $total += $tableContent->price;

}

現在在輸出電子郵件正文時,我們在這些變量中擁有所有項目和總數:


$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;

如您所見,我稍微更改了郵件的布局,因為購物車似乎可以包含多個項目,而您的電子郵件正文寫得好像只能包含一個。


關于這種方法的警告

您不應該在這樣的 POST 請求中從客戶端獲取購物車值,例如名稱和價格??蛻魬撝话l送商品 ID 和數量,然后您將從后端的數據庫或類似數據庫中獲取名稱和價格。否則,任何人都可以在發布之前將價格修改為他們想要的任何值。永遠不要相信用戶數據。


查看完整回答
反對 回復 2022-12-22
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號