ajax用户验证登录功能

原创 2019-06-28 21:13:43 431
摘要:login.php<!DOCTYPE html><html>    <head>      <title>ajax</title>    </head>    <body>       

login.php

<!DOCTYPE html>

<html>

    <head>

      <title>ajax</title>

    </head>

    <body>

        <h2>用户登录</h2>

        <p><input type="text" name="user" value=""></p>

        <p><input type="password" name="pwd" value=""></p>

        <button>登录</button>

    </body>

    <script>

        var btn=document.getElementsByTagName('button')[0];

        btn.onclick=function(){

            var xhr=new XMLHttpRequest();

            xhr.onreadystatechange=function(){

                if(xhr.readyState===4){

                    if(xhr.status===200){

                        var p=document.createElement('p');

                        var msg=JSON.parse(xhr.responseText);

                         

                        if(msg['state']==1){

                        p.innerHTML=msg['msg'];

                        }

                        if(msg['state']==0){

                        p.innerHTML=msg['msg'];

                        }

                        p.style.color='red';

                        document.body.appendChild(p);

                        setTimeout(function(){

                            document.body.removeChild(p);  

                        },2000)

                    }else{

                        alert('response fail'+xhr.status)

                    }

               }

            }

            xhr.open('post','check.php',true);

            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

            var data={

                user:document.getElementsByName('user').item(0).value,

                pwd:document.getElementsByName('pwd').item(0).value

            }

            var jsondata=JSON.stringify(data);

            console.log(jsondata);

            xhr.send('data='+jsondata);

       }

    </script>

</html>

check.php

<?php

    //print_r($_POST);

    $userdata=['user'=>'55308442@qq.com','pwd'=>'q123456'];

    $data=json_decode($_POST['data'],true);

    if( $data['user']==$userdata['user'] && $data['pwd']==$userdata['pwd']){

            $msgbox=['state'=>1,'msg'=>'登录成功'];

            exit(json_encode($msgbox)); 

        }else{

            $msgbox=['state'=>0,'msg'=>'用户名密码错误']; 

            exit(json_encode($msgbox));  

        }


批改老师:天蓬老师批改时间:2019-06-29 13:06:06
老师总结:前端的json字符串, 通过键值对的方式发送,其实可以通过原始json字符串直接发送的, 只是接收的时候,比较特殊,感兴趣, 可以搜索一下相关的课程

发布手记

热门词条