通过 php mail -ajax 发送购物车详细信息

我在一个 JS 购物车网站上工作,我正在尝试使用 php 邮件将购物车详细信息发送到结帐功能中的邮件,这里我通过 ajax 将我的购物车详细信息传递给 php。


在 php 中,当尝试使用 foreach 发送所有购物车值时,我只能接收购物车的最后一行,因为 foreach 正在重新计算先前的值


我如何检索购物车值并以某种格式发送它们


js


function SendMail() {

    var tableContent = localStorage.getItem('productsInCart');

    $.post('read.php', {tableContent: tableContent}, function (data) {

        console.log(tableContent);

    });

}

PHP


if (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");

}


aluckdog
浏览 69回答 1
1回答

喵喔喔

您目前正在循环的每次迭代中覆盖相同的变量,这就是为什么它们只包含最后一个条目的原因。您应该改为附加值,执行以下操作:$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 hereforeach ($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 和数量,然后您将从后端的数据库或类似数据库中获取名称和价格。否则,任何人都可以在发布之前将价格修改为他们想要的任何值。永远不要相信用户数据。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript