我正在尝试将一个简单的联系表单与ajax组合在一起,一旦提交完成,用户就不会被重定向到contact.php文件。
没有错误..我总是被重定向..
请问好吗?任何建议都非常感谢。谢谢!
contact.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form action="contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your Name">
</div>
<div>
<input type="email" name="email" placeholder="Your Email">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
<div>
<input type="submit" value="Send">
</form>
</body>
</html>
contact.php
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
print_r($_POST);
}
?>
main.js
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success:function(response) {
console.log(response);
}
});
return false;
});
答案 0 :(得分:0)
您需要阻止默认的表单行为。
$('form.ajax').on('submit', function(evt) {
evt.preventDefault();
答案 1 :(得分:0)
你需要输出json格式,所以标题需要设置,你需要将json值返回到ajax成功所以需要json_encode($ object_or_array_form_php);
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
header("Content-type:application/json");
$_POST['success'] = "You form is sending ...";
echo json_encode($_POST); //this is the "response" param form ajax
}
?>
答案 2 :(得分:0)
黑客攻击!这有点不同......
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-message").load("contact.php", {
name: name,
email: email,
message: message,
submit: submit
});
});
});
</script>