【问题标题】:Mailing form data with Fetch API使用 Fetch API 发送表单数据
【发布时间】:2018-10-08 20:04:33
【问题描述】:

我正在尝试使用 Fetch API 从表单中检索数据并将其邮寄,但我收到的电子邮件是空的。响应似乎成功,但没有发送数据。我做错了什么?

这是我的 JS 代码和我的 php/html sn-p(如果相关)

(function() {

  const submitBtn = document.querySelector('#submit');

  submitBtn.addEventListener('click', postData);

  function postData(e) {
    e.preventDefault();

    const first_name = document.querySelector('#name').value;
    const email = document.querySelector('#email').value;
    const message = document.querySelector('#msg').value;

    fetch('process.php', {
        method: 'POST',
        body: JSON.stringify({first_name:first_name, email:email, message:message})
    }).then(function (response) {
      console.log(response);
      return response.json();
    }).then(function(data) {
      console.log(data);
      // Success
    });

  }

})();



<!-- begin snippet: js hide: false console: true babel: false -->
<?php 
    $to = "example@mail.com"; 
    $first_name = $_POST['first_name'];
    $from = $_POST['email']; 
    $message = $_POST['message'];
    $subject = "Test Email";
    $message = $first_name . " sent a message:" . "\n\n" . $message;
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
?>


<form action="" method="post" class="contact__form form" id="contact-form">
  <input type="text" class="form__input" placeholder="Your Name" id="name" name="first_name" required="">
  <input type="email" class="form__input" placeholder="Email address" id="email" name="email" required="">
  <textarea id="msg" placeholder="Message" class="form__textarea" name="message"/></textarea>
  <input class="btn" type="submit" name="submit" value="Send" id="submit"/>
</form>

【问题讨论】:

    标签: javascript php ajax fetch fetch-api


    【解决方案1】:

    PHP 不理解 JSON 请求正文。所以当 JSON 文本发送给它时,PHP 不会自动解析 JSON 并将数据放入全局 $_POST 变量中。

    当正文只是文本时,fetch() 还将使用默认的 mime text/plain 作为内容类型。因此,即使您将body 设置为x-www-form-urlencoded 格式的数据,它也不会将请求标头设置为正确的标头,PHP 也不会正确解析它。

    您要么必须手动获取发送的数据并自己解析:

    <?php
    
    $dataString = file_get_contents('php://input');
    $data = json_decode($dataString);
    echo $data->first_name;
    

    通过显式设置内容类型标头并传递正确格式的body,以不同的内容类型发送数据,即application/x-www-form-urlencoded

    fetch('/', {
      method: 'POST',
      headers:{
        "content-type":"application/x-www-form-urlencoded"
      },
      body: "first_name=name&email=email@example.com"
    })
    

    或者甚至创建一个FormData 对象并让 fetch 自动检测要使用的正确内容类型:

    var data = new FormData();
    data.append('first_name','name');
    data.append('email','email@example.com');
    
    fetch('/', {
      method: 'POST',
      body: data
    })
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2022-11-16
      • 2018-03-20
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多