为了账号安全,请及时绑定邮箱和手机立即绑定

通过 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 请求中从客户端获取购物车值,例如名称和价格。客户应该只发送商品 ID 和数量,然后您将从后端的数据库或类似数据库中获取名称和价格。否则,任何人都可以在发布之前将价格修改为他们想要的任何值。永远不要相信用户数据。


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信