由于get方法提交有缓存,所以改用post
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax</title> </head> <body> <form > 邮箱: <input type="text" class="email" name="email" > <br> <span id="ti" style="color: red"></span> <br> <input id="sub" type="submit" onclick="ck();return false;" value="提交"> </form> </body> </html> <script type="text/javascript"> let sub=document.querySelector("#sub"); let ti=document.querySelector("#ti"); function ck() { let formData =new FormData(); let email=document.querySelector(".email"); formData.append('email',email.value); var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { let flag=xmlHttp.responseText; if(flag==0){ ti.innerText='邮箱错误'; }else{ ti.innerText='邮箱正确'; } } }; xmlHttp.open("post", "ck.php"); xmlHttp.send(formData); } </script>
php页面
<?php /** * Created by PhpStorm. * User: hello word! * Date: 2019/3/23 * Time: 15:25 */ if($_POST){ $email=$_POST['email']; $preg_email='/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims'; if(preg_match($preg_email,$email)){ echo 1; }else{ echo 0; } }
效果图: