lon*_*mar 0 javascript php ajax fetch fetch-api
我正在尝试使用Fetch API从表单中检索数据并将其邮寄,但是我收到的电子邮件为空。响应似乎成功,但未发送任何数据。我究竟做错了什么?
这是我的JS代码和我的php / html代码段(如果相关)
(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 -->Run Code Online (Sandbox Code Playgroud)
<?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>Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
将数据作为其他内容类型发送,即application/x-www-form-urlencoded通过显式设置content-type标头并传递正确的格式body:
fetch('/', {
method: 'POST',
headers:{
"content-type":"application/x-www-form-urlencoded"
},
body: "first_name=name&email=email@example.com"
})
Run Code Online (Sandbox Code Playgroud)
甚至创建一个FormData对象,然后让fetch自动检测要使用的正确内容类型:
var data = new FormData();
data.append('first_name','name');
data.append('email','email@example.com');
fetch('/', {
method: 'POST',
body: data
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2380 次 |
| 最近记录: |