gpt4 book ai didi

javascript - 在div中显示文本而不重新加载页面

转载 作者:行者123 更新时间:2023-12-03 11:41:31 25 4
gpt4 key购买 nike

在下面的代码中,我有一个联系表单,该表单中有一个电子邮件验证脚本。作为验证的结果,我希望错误消息显示在名为“确认”的 div 中,而无需重新加载页面。另外,如果电子邮件有效,则会发送邮件,并且我希望在同一 div 确认中显示感谢消息。问题是我该如何防止重新加载页面并让错误消息或感谢消息显示在确认 div 中?

<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>

<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11@gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>

谢谢

最佳答案

<input type="text" name="from" id ="from">

调用示例:

var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});

request.done(function( msg ) {
//handle HTML
});

request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});

PHP 端

<?php

$email = $_POST["email"]

function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}

echo spamcheck($email);

关于javascript - 在div中显示文本而不重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257230/

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