gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:58:38 25 4
gpt4 key购买 nike

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

最佳答案

Click 事件在 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>

关于javascript - 使用ajax发送数据,然后发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25959434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com