javascript - 使用ajax将表单提交给php而不刷新页面
问题描述
有人可以告诉我为什么这段代码不起作用我想通过 post 方法将表单数据发送到 PHP 但我的 PHP 没有收到任何请求这里是我的注册表单 signupmodal.php
<form action="<?php htmlentities($_SERVER['PHP_SELF']) ?>" method="post" id="signupForm">
<div class="form-group">
<label for="forUserName">User Name:</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Enter User Name" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="forEmail">Email:</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Enter Your Email" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="">password:</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter Password" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="forConfirmPassword">Confirm Password</label>
<input type="password" name="cpassword" id="cpassword" class="form-control" placeholder="Enter Confirm Password" aria-describedby="helpId">
</div>
<input type="submit" class="btn btn-primary" value="SignUp" id="subbtn" onclick="myFunction()">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<?php echo json_encode($_POST);
// echo $_POST['email'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
echo $username;
if ($password == $cpassword) {
//code
} else
echo '<div class="alert alert-danger" role="alert">
<strong>danger</strong>
</div>';
} ?>
</div>
script.js
function myFunction() {
console.log(window.location.href);
$('form').on('submit', function (event) {
$.ajax({
type: 'POST',
url: 'includes/signupmodal.php',
data: $('form#signupForm').serialize(),
success: function () {
data = $('form#signupForm').serialize();
console.log(data);
},
});
event.preventDefault();
});
}
我想在不加载页面的情况下使用 ajax 提交我的数据,所以请告诉我我错在哪里
解决方案
您仅myFunction()
在单击提交按钮时才运行,到那时添加提交事件侦听器为时已晚。
我建议您在文档准备好后添加您的侦听器。
从您的提交按钮中删除onclick="myFunction()"
并将其添加到您的脚本
jQuery(function() {
myFunction() // executes when the document has completely loaded
})
// or even just
// jQuery(myFunction)
推荐阅读
- algorithm - 检查总零集
- python - 如何正确解析python函数文档字符串?
- jquery - 来自 Flask send_file 的 Zip 文件无效
- javascript - 使用 Javascript 填写 iframe 中的输入字段
- html - 如何滚动到带有额外空格(固定标题)的 HTML id 标签?
- rest - 我应该在导致空集的资源上返回 404 错误吗?
- python-3.x - Pandas: operations between multiindex dataframes
- javascript - MySQL NodeJS 准备好插入或更新表名的语句?
- matlab - Matlab:如何将块组合回原始矩阵?
- html - IE 中未显示锚标记