使用ajax发送数据,然后发送电子邮件

send data using ajax and then send email

本文关键字:然后 电子邮件 数据 使用 ajax      更新时间:2023-09-26

我正在尝试创建一个脚本,当有人单击按钮时,该脚本将向我们公司的电子邮件发送电子邮件。html将托管在一个静态页面上,并在客户端执行所有操作,而php代码将托管在另一个域上。

到目前为止,我尝试过的是

HTML

<head><title>Report Errors</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' type='text/javascript'></script></head>
<script>$(".c").click(function(){
var href = this.href;
        $.ajax({
        url: 'http://example.com/m35.php',
        type: 'POST',
        data: { subject: href },
        success: function (data) {
                    setTimeout(function (){
                    $(".container").html(data)
                    }, 1000)
                }
        });
    })
</script>
<a href="http://link-to-be-sent.example.com" class="c">send</a>
<div class="container">success</div>

以及m35.php文件中的代码-

<?php  
$mailTo = "mail@example.com"; 
$mailFrom = "no-reply@example.com";  
$subject = $_POST["subject"];
$message = "someone reported the content in subject doubtful.";  

mail($mailTo, $subject, $message, "From: ".$mailFrom);  
?>

编辑:基于评论,我想澄清一下,它甚至不适用于同一个域和目录,然而,这种类型的代码也在工作,但如何在不使用javascript/jquery重新加载页面的情况下做到这一点。

<form method="post" action="http://example.com/m35.php">
<input type="text" name="subject" id="subject" value=""> <input type="submit">
</form>

在呈现dom元素之前附加Click事件。所以它没有被解雇。$(".c")a html元素,因此单击后,它将加载另一个页面。在这种情况下,ajax请求可能无法到达服务器。为了防止这种js代码应该在$(document).ready()事件中,并使用return false;从点击事件阻止页面加载:

<script>
$( document ).ready(function(){
    $(".c").click(function(){
        var href = this.href;
        $.ajax({
            url: 'http://example.com/m35.php',
            type: 'POST',
            data: { subject: href },
            success: function (data) {
                setTimeout(function (){
                    $(".container").html(data)
                }, 1000);
            }
        });
        return false; // prevent load to another page
    });
});
</script>