lqf4203 2019-02-24 10:21 采纳率: 0%
浏览 490
已结题

原生ajax提交请求readyState=1

在做表单验证的时候出现的问题,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';
}       
?>
  • 写回答

1条回答 默认 最新

  • gpl0111 2019-02-25 16:01
    关注

    url直接写login.php试试?

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器