我有一个将用户插入数据库的表单。另一方面,我有两个密码验证脚本和 ajax 脚本,用于检索 php 结果。
现在这两个脚本正在单独工作。
我应该怎么做才能在密码验证后运行 ajax 脚本?
密码验证
function Validate() {
var password = document.getElementById("UserPwd").value;
var confirmPassword = document.getElementById("ConfirmUserPwd").value;
if (password != confirmPassword) {
alert("Please enter the same password");
return false;
}
return true;
}
脚本
$.ajax({
url: "insert_sp.php",
method: "POST",
data: {submit: 'true'},
success: function(response) {
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
更新
设置:if(isset($_POST['Submit']))
按钮:<input type="submit" name="Submit" value="Submit"/>
$(function() {
$("#myForm").on("sumbit", function(e) {
e.preventDefault();
var password = $("#UserPwd").val(),
confirmPassword = $("#ConfirmPassword").val();
if ($.trim(password) === password &&
password !== "" &&
password === confirmPassword) {
$.ajax({
url: "insert_sp.php",
method: "POST",
data: {
submit: 'true'
},
success: function(response) {
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
}
else {
alert("Please enter the same password");
}
});
});
最佳答案
切勿在表单中将任何内容称为“提交”。如果您需要,它将隐藏提交事件。
使用表单的提交事件和 event.preventDefault 而不是提交按钮点击事件
如果你有 jQuery,为什么不一直使用它呢?
请记住在插入之前在服务器上执行完全相同的验证
我无法为您提供运行片段,因为 SO 不允许在其页面中提交。这是代码 - 它应该按设计工作
$(function() {
$("#myForm").on("submit", function(e) {
e.preventDefault(); // cancel form submission
var password = $("#UserPwd").val(),
confirmPassword = $("#ConfirmPassword").val();
console.log(password,confirmPassword)
if ($.trim(password) === password && // spaces?
password !== "" && // empty?
password === confirmPassword) { // the same?
$.ajax({
url: "insert_sp.php",
method: "POST",
data: {
Submit: 'true' // remember to change the $_POST test too
},
success: function(response) {
var data = $.parseJSON(response);
console.log(data);
}
});
} else {
alert("Please enter the same password");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="password" value="" id="UserPwd" /><br/>
<input type="password" value="" id="ConfirmPassword" /><br/>
<input type="submit" name="Submit" value="Submit" />
</form>
关于javascript - 密码验证后发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42757312/