通过Ajax将数据发送到PHP?

时间:2016-10-15 07:04:11

标签: php jquery ajax post swiftmailer

我需要发送电子邮件,当我向mail.php发送请求时,数据值为空。我无法弄清楚为什么会发生这种情况,并尝试了很多不同的事情。

AJAX:

$.ajax({
url: 'mail.php',
action: 'POST',
data: {
    'name_first': "First",
    'name_last': "Last",
    'title': "Test Title",
    'topic': "Test Topic",
    'mailer': "example@example.com",
    '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('business@astronstudios.com')
    ->setPassword('...');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance("[" . $inf_topic . "] " . $inf_title)
    ->setFrom(array($inf_mailer => $inf_name))
    ->setTo(array('business@astronstudios.com' => 'AstronStudios'))
    ->setBody($inf_message, 'text/html');

return $mailer->send($message);

3 个答案:

答案 0 :(得分:2)

设置type属性而不是action来设置AJAX请求的方法(GETPOST)。所以代码看起来像这样,

$.ajax({
url: 'mail.php',
type: 'POST',
data: {
    'name_first': "First",
    'name_last': "Last",
    'title': "Test Title",
    'topic': "Test Topic",
    'mailer': "example@example.com",
    '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);
}});

参考:http://api.jquery.com/jquery.ajax/

答案 1 :(得分:1)

var formdata = new FormData($('form')[0]);
$.ajax({
url: 'mail.php',
type: 'POST',
data: formdata ,
success: function (response) {
        if(data.response === 'success') {
 alert(response);
}else{
alert(response);
}
},
});

答案 2 :(得分:1)

设置“type”而不是“action”