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

时间:2014-09-21 12:58:15

标签: javascript php jquery ajax

我正在尝试创建一个脚本,当有人点击按钮时,该脚本会向我们公司的电子邮件发送电子邮件。 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>

1 个答案:

答案 0 :(得分:2)

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

<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>
相关问题