php - 在模式窗口中发送表单
问题描述
对不起,我开始这个话题。我知道这件事有很多话题。但我仍然无法处理它,因为我需要将成功/失败消息显示如下:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
我的意思是在不重新加载页面的情况下提交此表单(因为它位于模式窗口中),并且我必须在表单中显示成功/失败消息(也无需重新加载页面)。我不知道怎么做。
我将不胜感激如何一步一步地提供帮助和解释。
解决方案
您的 PHP 脚本在页面重新加载时执行,因此在使用 Ajax 时,您必须手动显示来自服务器的消息:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})
推荐阅读
- c# - C# 和 C++ 之间 Rijndael 加密差异的结果
- ionic-framework - 离子:避免滚动输入焦点
- junit - 具有非 Junit 断言方法的 TestMethodWithoutAssertion 的 JQassistant 规则
- java - Spring Boot项目中Drools规则引擎中的GC内存不足
- c - C 数组 memcmp 麻烦
- sublimetext3 - 如何摆脱 Sublime Text 3 上的多个窗格?
- python - Python 中的 Fibonacci o/p 不正确,因为未在同一行代码上分配值。为什么?
- node.js - 在 Log4js 中如何启用跟踪?
- angular - 我想用 Angular2 检查是否存在文件
- angular - 打开模态窗口组件