【问题标题】:Converting JavaScript array to PHP using fetch and then sending email使用 fetch 将 JavaScript 数组转换为 PHP,然后发送电子邮件
【发布时间】:2019-05-28 02:04:02
【问题描述】:

我正在努力尝试将我的 JavaScript 电子邮件数组转换为 PHP 数组,然后我可以使用本地主机将电子邮件发送回。

我的 html 中有一个输入字段,由用户(一次一个)填充,它使用 JavaScript 中的 .push 将它们放入数组中。我尝试使用 fetch 将此数组转换为 PHP,然后我可以使用 PHPMailer 将电子邮件发送回电子邮件地址。

电子邮件不会以数组的形式出现在我的控制台中,但如果我将内容类型更改为“Content-Type”:“application/x-www-form-urlencoded”就会出现。但是,电子邮件仍然没有以这种方式发送。

这仅适用于一个小型 uni 项目,这就是为什么我只关心通过本地主机发送电子邮件,因为我不会在任何地方托管该项目。

HTML:

<input type="text" id="names" placeholder="Name" />
<input type="text" id="emails" placeholder="Email address" />
<input type="button" onclick="addTo()" value="Add" />

<input type="button" id="done-button" onclick="completed()" value="Done" />

JavaScript:

var names = [];
var emails = [];
var allNumbers = [];

function addTo() {
    names.push(document.getElementById("names").value);
    document.getElementById("names").value = "";
    emails.push(document.getElementById("emails").value);
    document.getElementById("emails").value = ""; 
}

function completed() {
    var numbers = names.length;
        for (var i = 1; i <= numbers; i++) {
            allNumbers.push(i);
        }

    fetch("http://localhost:8888/fetchme.php", {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "no-cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json"
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: emails // body data type must match "Content-Type" header
    }).then((response) => {console.log(response)}); // parses response to console
}

PHP:

<?php 
var_dump($_POST);

use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "example@gmail.com";
$mail->Password = "password";
$mail->setFrom('example@gmail.com', 'Example');

$emails = json_decode($_POST);

if (isset($emails)) {
    foreach ($emails as $email) {
        $mail->addAddress($email);
        $mail->Subject = 'Your Results';
        //Read an HTML message body from an external file, convert referenced images to embedded,
        //convert HTML into a basic plain-text alternative body
        //$mail->msgHTML(file_get_contents('index.html'), __DIR__);
        $mail->Body = 'Hello, this is my message.';
        $mail->AltBody = 'This is a plain-text message body';
        if (!$mail->send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message sent!";
        }
    }
}
?>

【问题讨论】:

  • exit 在它运行后停止任何东西。
  • 如果您在正文中以 json 格式发布数据,您可能需要使用 $json = file_get_contents('php://input'); 获取它。你可以阅读更多关于区别here
  • $emails = json_decode($_POST); 毫无意义。通常的方法见@MagnusEriksson 评论。

标签: javascript php arrays localhost fetch


【解决方案1】:

fetch() 与数组一起用作正文不会发送 JSON 字符串。发送到服务器的是一个逗号分隔的电子邮件地址列表。无论如何,PHP 不会将它们放入$_POST,因为正文不是有效的查询字符串。

首先,您应该使用JSON.stringify()emails 数组转换为JSON 字符串。然后,在 PHP 中,您可以使用 http_get_request_body() 读取请求正文。

或者,您可以构建查询字符串将其设置为请求的正文,然后您就可以正常使用$_POST

【讨论】:

    【解决方案2】:

    尝试使用 class 而不是 id 来填写姓名和电子邮件, 如果在将其传递给 PHP 之前在 javascript 中获取值,则尝试使用控制台日志在 javascript 本身中获取值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      相关资源
      最近更新 更多