【发布时间】:2020-08-09 03:17:45
【问题描述】:
这里是html表单
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="form" action="" name="form" class=" f-color " >
<div class="form-group ">
<label for="contactusername">Name</label>
<input type="text " name="name" class="form-control " placeholder="Enter Your Name" id="contactusername " required>
</div>
<div class="form-group ">
<label for="contactemail ">Email</label>
<input type="email " name="email" class="form-control " placeholder="Enter Your Email" id="contactemail " required>
</div>
<div class="form-group ">
<label for="contactcomment ">Your Message</label>
<textarea name="msg" class="form-control " placeholder="Enter Your Message Here" rows="5 " id="contactcomment " required></textarea>
</div>
<input type="submit" name="submit" value="Send" class="btn btn-block bg-light mt-4 py-3 text-uppercase font-weight-bold">
</form>
</body>
</html>
使用的 Ajax 代码
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
process.php在这里
<?php
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['msg'];
$to='email@gmail.com';
$subject='Form submission';
$message="Name: ".$name."\n"."message:".$message;
$headers="From: ".$email;
if(mail($to, $subject, $message, $headers))
{
echo "<h1>Sent success! Thank you"." ".$name."</h1>";
}
else{
echo "Something went wrong!";
}
}
?>
当我在表单上执行 process.php 时,我在我的电子邮件上收到表单提交,但页面更改为带有成功消息的空白页面。为避免这种情况,我尝试使用 ajax 但失败了。作为初学者,我卡在某个地方。帮我解决这个问题,如何在同一窗口上显示“提交成功”消息?。
【问题讨论】:
-
当您通过 AJAX 提交时,
if(isset($_POST['submit']))不会为真 - 按下的提交按钮不会 成为带有.serialize的表单提交数据集的一部分。跨度>