我正在尝试使用jquery和php在jquery上使用post方法验证前端和后端的表单数据。
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
这是我的表单,我如何在不刷新页面的情况下在前端和后端对其进行验证
答案 0 :(得分:0)
<script>
$(document).ready(function(){
$("button").on("click", function(){
let email = $.trim($("#exampleInputEmail1").val());
let password = $.trim($("#exampleInputPassword1").val());
if(email === ""){
alert("Email is required!");
return false;
}
if(password === ""){
alert("Password is required!");
return false;
}
$.post("login.php",{email : email , password : password}, function(response){
response = JSON.parse(response);
if(response.success){
// redirect to homepage
}else{
alert(response.message);
}
});
});
});
</script>
login.php
<?php
$email = $_POST["email"];
$password = $_POST["password"];
if($email === ""){
echo json_encode(array("success" => false,"message" => "Email is required!"));
exit;
}
if($password === ""){
echo json_encode(array("success" => false,"message" => "Password is required!")); exit;
}
//check the record in db and send back the response
?>