如何使用 JQuery 和 PHP 通过 POST 提交 attr 值和表单值


How to submit attr value and form values with POST using JQuery and PHP?

所以我有一个带有输入框和 3 种div的表单,单击时会突出显示。我正在尝试让它提交属性和"#email"值并通过 PHP 通过电子邮件发送给我。

这是我的 HTML:

<form id="form" name="form" class="custompurchase" action="custom.php" method="post">
    <input type="email" id="email" name="email" maxlength="40" class="textbox2" placeholder="Email address" required/>
    <a class="customoption storage" onclick="activate(this, 'storage');" data-name="500GB HDD">
        ...
    </a>
    <a class="customoption storage" onclick="activate(this, 'storage');" data-name="1TB HDD">
        ...
    </a>
    <a class="customoption storage" onclick="activate(this, 'storage');" data-name="2TB HDD">
        ...
    </a>
</form>

这是我的 JQuery:

$(function() {
    var form = $('#form');
    $(form).submit(function(event) {
        event.preventDefault();
        var email = $("#email").val();
        var storage = $(".customoptionactive.storage").attr("data-name");
        $.ajax({
            type: "POST",
            url: $(form).attr("action"),
            data: email, storage
        })
        .done(function(response) {
            ...
        });
    });
});

最后是我的PHP:

<?php
    $emailto = "purchases@prismpc.net";
    $subject = "Custom PC";
    $email = $_POST['email'];
    $storage = $_POST['storage'];
    $entire = "Email: ".$email."'n"."Storage: ".$storage;
    mail($emailto, $subject, $entire);
?>

但是,当我看到电子邮件时,这就是我得到的全部内容:

Email:
Storage:

我做错了什么?我需要设置dataType吗?非常感谢您的回答!

编辑:与类似问题不同,因为它是一个简单的语法错误。

更改$.ajax上的data选项

 data: email, storage

 data: {email:email, storage:storage}

您可能希望使用FormData并将自定义数据附加到其中,正如Manta在这里指出的那样: 通过JQuery AJAX一起发送FormData和字符串数据?

var formData = new FormData();
formData.append('storage', $(".customoptionactive.storage").attr("data-name"));
$.ajax({
    type: "POST",
    url: $(form).attr("action"),
    data: formData
})
.done(function(response) {
    ...
});

这将节省您手动添加这些输入值的时间