美好的一天/晚上。我在HTML中有这种形式:
<form action="scripts/form-testimonial.php" class="form" method="post">
<ul>
<li><label for="name">Name</label> <input class="required" id="namef3" name="name" placeholder="Name" type="text"></li>
<li><label for="email">E-mail</label> <input class="required" id="emailf3" name="email" placeholder="E-mail" type="text"></li>
<li><label for="company">Company</label> <input id="companyf3" name="company" placeholder="Company (if applicable)" type="text"></li>
<li><label for="msg">Message</label> <textarea class="required" cols="43" id="msgf3" name="msg" placeholder="Your feedback" rows="8"></textarea></li>
</ul>
<button class="submit" type="submit">Send your feedback</button>
</form>
和这种形式的php作为一个单独的文件sript:
<?php
$receip = "office@avehire.co.uk";
$subj = "Testimonial";
$bodymsg = "Name: ".$_POST['name']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Message: ".$_POST['msg']."\n";
if(!$_POST['msg']){
header("Location: ../error.html");
exit;
}
$email = $_POST['email'];
if(mail($receip, $subj, $bodymsg, 'From: Contact <'.$email.'>')){
header("Location: ../msg_sent_feedback.html");
}
?>
我也有这个表格的验证器,但这并不重要。这里更重要的是这种形式的工作方式。基本上 - 当你点击提交按钮 - 它会转到一个单独的php文件,处理表单,然后 - 从已经存在的 - 转到msg_sent_feedback.html文件。我想要做的是不打开一个单独的文件,只是在存在实际表单的相同基本html文件中显示一条消息。例如一条消息“发送消息”。
另一件事 - 如果我已经有验证脚本 - 我是否需要在此表单中使用第一个“if”?或者我可以完全删除它吗?重定向到error.html的那个。或者我可以删除这4行吗?那条线 - 我想 - 负责表单中的错误,但正如我所提到的,我有一个验证脚本。我真的不想改变HTML。是否有可能修改PHP脚本在html文档中工作,如上所述?感谢
答案 0 :(得分:1)
这是一个可以帮助你的Jquery ajax示例。
<?php
$receip = "office@avehire.co.uk";
$subj = "Testimonial";
$bodymsg = "Name: ".$_POST['name']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Message: ".$_POST['msg']."\n";
if(!$_POST['msg']){
echo "<h1>Error sending e-mail";
exit;
}
$email = $_POST['email'];
if(mail($receip, $subj, $bodymsg, 'From: Contact <'.$email.'>')){
echo "<h1>Email sent successfully</h1>";
}
?>
Html:
<!Doctype html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function submitmyform(){
data=$('#myform').serialize();
$.ajax({
url: "myphpfile.php",
type:'POST',
data:data,
async:false,
dataType:'html',
success: function(msg){
$('#response_goes_here').html(msg);
}
});
}
</script>
<form action="" id="myform">
<ul>
<li> <label for="name">Name</label> <input id="namef3" name="name" type="text" placeholder="Name" class="required"/>
</li>
<li> <label for="email">E-mail</label> <input id="emailf3" name="email" type="text" placeholder="E-mail" class="required"/>
</li>
<li> <label for="company">Company</label> <input id="companyf3" name="company" type="text" placeholder="Company (if applicable)" />
</li>
<li> <label for="msg">Message</label> <textarea id="msgf3" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>
</li>
</ul>
<button type="button" class="button" onclick="submitmyform();">Send your feedback</button>
</form>
<div id="response_goes_here"></div>