gpt4 book ai didi

javascript - Jquery、PHP 和 Ajax 表单无刷新

转载 作者:行者123 更新时间:2023-11-29 21:40:15 25 4
gpt4 key购买 nike

我尝试在不刷新的情况下使用 jquery、ajax 和 php 准备简单的联系表单。除了 event.preventDefault();

之外一切正常

这是我的文件:

contact_engine.php

<?php

$name = $_POST['name'];
...


$from = 'from';
$to = 'to';
$subject = 'subject';
$human = '4';

$body = ".........";

if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thanks</p>';
} else {
echo '<p>Error</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>

Ajax /jQuery

$('form').on('submit', function(event){
event.preventDefault();
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
}
});
});

PHP

<form method="post" action="<?php bloginfo('template_directory'); ?>/contact_engine.php">       
<div class="box">
<input type="text" name="name" class="pola formbg name" placeholder="Name" />
.
.
.
.

<p><input id="form-button" type="submit" name="submit" value="Send" /></p>
</div>
<br style="clear: left;" />
</form>

当我删除 event.preventDefault(); 时,一切正常,我从表单收到一条消息,但网站正在刷新,我看到“谢谢”消息。

如您所见,我使用的是 Wordpress。

最佳答案

是的,在这种情况下为什么要有表单/提交按钮。删除表单并将输入从提交按钮更改为标准按钮。将功能放在按钮上,工作完成。

$('#form-button').on('click', function(event){

$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
//do something with the return code
}
});
});

关于javascript - Jquery、PHP 和 Ajax 表单无刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33216242/

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