【问题标题】:Sending data to PHP via Ajax?通过 Ajax 向 PHP 发送数据?
【发布时间】:2017-02-24 15:34:47
【问题描述】:

我需要发送一封电子邮件,当我向 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);

【问题讨论】:

    标签: php jquery ajax post swiftmailer


    【解决方案1】:

    设置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/

    【讨论】:

    • 谢谢!在这么简单的问题上花了这么长时间。
    【解决方案2】:
    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);
    }
    },
    });
    

    【讨论】:

      【解决方案3】:

      设置“类型”而不是“动作”

      【讨论】:

      • 在 js 中你必须使用“type”而不是“action”
      猜你喜欢
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 2012-03-18
      • 2015-10-27
      • 2011-10-19
      • 2014-04-26
      • 2017-05-10
      相关资源
      最近更新 更多