在做表单验证的时候出现的问题,ajax提交请求readyState停留在1,status=502 503 504,百度上的方法基本都看过了,但就是解决不了。如果不用ajax,直接从提交表单却可以验证成功。请各位大佬们帮忙看看 。
表单代码:
<form action ="" method="post" name="login_form" id="login_form">
<div class="lgD">
<img src="img/u.jpg" width="20" height="20" alt=""/>
<input type="text" name="userName" id="userName" autocomplete="off" placeholder="输入用户名" />
</div>
<div class="lgD">
<img src="img/p.jpg" width="20" height="20" alt=""/>
<input type="password" name="password" id="password" autocomplete="off" placeholder="输入用户密码" />
</div>
</form>
<div class="logC">
<button type="button" id="submit" >登 录</button>
</div>
ajax代码:
<script>
var submit = document.getElementById('submit');
submit.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
alert(xhr.readyState+xhr.status);//获取到readyState一直是1 status=502 503 504
if(xhr.readyState ==4 && xhr.status == 200){
alert(xhr.responseText);
}
}
var user = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var data = 'userNamae='+user+'&password='+password;
var url = 'http://localhost/login.php';
xhr.open('post',url,true);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data);
return false;//禁止默认行为
}
</script>
后端:
<?php
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
$userName = $_POST['userName'];
$password = $_POST['password'];
$con = mysqli_connect("localhost","root","123456","company_db");
if (!$con) {
die("database false to connected" . mysqli_connect_error());
}
$sql = "SELECT *FROM admin WHERE userName = $userName";
if(!$sql){
echo 'User not exist';
}
$res = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($res);
if($row > 0 && $password==$row["pwd"]){
echo 'ok';
}else{
echo 'failed';
}
?>