【发布时间】: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