0

我在使用 Ajax 到 PHP 解析数组以发送包含数组值的电子邮件时遇到困难。

阿贾克斯代码:

    $(document).ready(function(){

            $("#submit-button").click(function(){

                var countryArray = ['Location Zero', 'Location One', 'Location Two'];

                dataString = countryArray; 
                var jsonString = JSON.stringify(dataString);

                $.ajax({
                        type: "POST",
                        url: "sendmail.php",
                        data: {countries: jsonString},
                        success: function (msg) {

                            $("#errors").text("Thank you for getting in touch, we will get back to you!");

                        },
                        error: function (msg) {
                            $("#errors").text("Error sending email, please try again.");

                            alert("error");
                        }
                    });


});

});

PHP代码:

<?php


        $to = "abc@abc.com";
        $countries = json_decode($_POST['countries']);

        $header = "Content-Type: text/html\r\nReply-To: \r\nFrom:  <>";
        $subject = "Email from the Lister customer";

        $body = @"$countries";


        if(mail($to, $subject, $body, $header)) {
            die("true");    
        } else {
            die("There was an error sending the email.");   
        }


?>

但是我在电子邮件中得到的$countries只是单词“Array”而不是值。

有人可以帮忙吗?

4

3 回答 3

3

$countries是一个数组。如果您希望它在您的 中显示为列表$body,您可以执行以下操作:

$body = implode(', ', $countries);

也请尽量不要压制 ( @) PHP 错误,这会在未来让您更加头疼。

于 2013-06-11T14:42:07.790 回答
0

如果您使用的是 jquery,请尝试使用.serializeArray()而不是 stringify。

此外,在接收 $_POST['contries'] 变量时,您需要将其内爆。尝试这个:

$(document).ready(function(){
    $("#submit-button").click(function(){
        var countryArray = ['Location Zero', 'Location One', 'Location Two'];
        $.ajax({
            type: "POST",
            url: "sendmail.php",
            data: {countries: countryArray.serializeArray()},
            success: function (msg) {
                $("#errors").text("Thank you for getting in touch, we will get back to you!");
            },
            error: function (msg) {
                $("#errors").text("Error sending email, please try again.");
                alert("error");
            }
        });
    });
});

然后在 PHP 中使用它来正确获取国家值:

implode(', '.$countries);
于 2013-06-11T14:56:05.467 回答
0
<?php


    $to = "abc@abc.com";
    $countries = json_decode($_POST['countries']);

    $header = "Content-Type: text/html\r\nReply-To: \r\nFrom:  <>";
    $subject = "Email from the Lister customer";

    $body = implode(", ", $countries);


    if(mail($to, $subject, $body, $header)) {
        die("true");    
    } else {
        die("There was an error sending the email.");   
    }
?>
于 2013-06-11T14:42:21.713 回答