我需要发送一封电子邮件,当我向mail.php发送请求时,数据值为空。我无法弄清楚为什么会发生这种情况,并且尝试了多种不同的方法。
ajax:
$.ajax({
url: 'mail.php',
action: 'POST',
data: {
'name_first': "First",
'name_last': "Last",
'title': "Test Title",
'topic': "Test Topic",
'mailer': "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e1fce5e9f4e8e1c4e1fce5e9f4e8e1aae7ebe9" rel="noreferrer noopener nofollow">[email protected]</a>",
'mail': "This is a message"
},
success: function (response) {
alert(response)
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}});
php:
<?php
require_once 'swiftmailer/lib/swift_required.php';
$inf_name = $_POST['name_first'] . ' ' . $_POST['name_last'];
$inf_title = $_POST['title'];
$inf_topic = $_POST['topic'];
$inf_mailer = $_POST['mailer'];
$inf_message = $_POST['mail'];
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
->setUsername('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="274552544e4942545467465453554849545352434e48540944484a" rel="noreferrer noopener nofollow">[email protected]</a>')
->setPassword('...');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance("[" . $inf_topic . "] " . $inf_title)
->setFrom(array($inf_mailer => $inf_name))
->setTo(array('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89ebfcfae0e7ecfafac9e8fafdfbe6e7fafdfcede0e6faa7eae6e4" rel="noreferrer noopener nofollow">[email protected]</a>' => 'AstronStudios'))
->setBody($inf_message, 'text/html');
return $mailer->send($message);
最佳答案
设置type
属性而不是action
来设置AJAX请求的方法(GET
或POST
) 。所以代码看起来像这样,
$.ajax({
url: 'mail.php',
type: 'POST',
data: {
'name_first': "First",
'name_last': "Last",
'title': "Test Title",
'topic': "Test Topic",
'mailer': "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62071a030f120e0722071a030f120e074c010d0f" rel="noreferrer noopener nofollow">[email protected]</a>",
'mail': "This is a message"
},
success: function (response) {
alert(response)
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}});
关于php - 通过 Ajax 向 PHP 发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40056094/