我有一个电子邮件输入字段和一个提交按钮,按下该按钮时我希望文本字段发生变化,告诉用户他们已订阅。由于某种原因,电子邮件字段没有将输入的电子邮件转发到 php 文件。但是我知道 php 正在执行,因为它每次都会给我一个订阅错误。这里还提出了另一个类似的问题,但解决方案不起作用。
我认为这是使用 <form>
的问题和<button>
结合起来,但我不知道执行此操作的正确方法,有什么想法吗?
HTML:
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>Community Sound</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "phEmail.php", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
<body>
<!-- Subscription -->
<div class="container">
<div class="no-result vertical-align-outer">
<div class="vertical-align">
<form method="post" >
<input name="email" class="email glowing-border" type="email" placeholder="Enter your email address ...">
<button type="button" onclick="return getData()" class="emailbtn">Subscribe</button>
</form>
</div>
</div>
</div>
<div id="div1">Not Subscribed</div>
</body>
</head>
PHP:
<?php
$to = "garvernr@mail.uc.edu";
$from = "newsubscription@samplepackgenerator.com";
$headers = "From: " . $from . "\r\n";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo 'You have been added to our mailing list!';
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
?>
最佳答案
您可以通过表单发布将表单数据发送到另一个页面,也可以发出 ajax 调用。目前,您正在尝试介于两者之间的操作,并且有两个 onClick
处理程序,一个在控件本身 onclick="return getData()"
中,另一个通过 jQuery 添加。
第一个完全丢失,上面的第二个(jQuery AJAX)不发送任何数据。
这样改变:
....
<button type="button" id="sendbutton" class="emailbtn">Subscribe</button>
....
还有你的ajax:
$(document).ready(function(){
$("#sendbutton").click(function(){
$.ajax({
url: "phEmail.php",
data: { "email": $('#sendbutton').val() },
success: function(result){
$("#div1").html(result);
}});
});
});
当您熟悉了这一点后,您可以考虑一次性序列化整个表单,这会更通用。查看 jQuery 文档来了解这一点
关于javascript - 电子邮件表单不携带电子邮件到 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460945/