【问题标题】:send data using ajax and then send email使用 ajax 发送数据,然后发送电子邮件
【发布时间】:2014-11-15 13:18:41
【问题描述】:

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

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

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

【问题讨论】:

  • 这是一个 CORS 问题,您无法使用 AJAX 将数据发送到其他域。
  • 也许这会有所帮助? stackoverflow.com/questions/17318426/…
  • 感谢@Scimonster 的建议,但这甚至不适用于同一个域
  • 为什么你说它不起作用? php代码执行了吗?客户端或服务器端是否有任何错误?
  • 这个脚本做的唯一一件事就是向mailto中指定的地址发送一封电子邮件,当我通过在地址栏中输入example.com/m35.php并更改$主题直接加载页面时,这个脚本可以工作。

标签: javascript php jquery ajax


【解决方案1】:

在渲染 dom 元素之前附加点击事件。所以它没有被解雇。 $(".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>

【讨论】:

  • 谢谢修复,但它仍然没有发送电子邮件。通过表单提交时查看更新后的问题。
  • 如果你点击a html 元素它会加载另一个页面并且js 代码可能不会被执行。查看我所做的修改。
  • 对此表示赞同。谢谢这一切都奏效了。你知道如何在不同的域上同时运行 html 和 php。
  • 查看this question 了解如何在 php 中启用 CORS。如果您觉得满意,可以接受我的回答;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多