Blogger Information
Blog 36
fans 1
comment 0
visits 32462
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax工作原理_用户登陆验证_2018年9月13日
宋超的博客
Original
888 people have browsed it

一.Ajax工作原理
Ajax简单来说就是通过客 户端向服务器发出异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面,在此期间页面不会进行跳转就会看到返回的数据,对用户体验比较友好;另一方便因为Ajax都是异步请教数据,而通过js操作DOM来返回数据,所以在对搜索引擎的友好度上要差些.
Ajax常用在用户提交数据验证,以及实时数据交互的场景中,比如QQ空间发表的说说,微博,各大网站的留言评论等.
二.Ajax验证登陆

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <style>
        div{
            width: 400px;
            max-height:300px;
            margin: 20px auto;
            padding: 10px 50px 10px 60px;
            box-shadow:10px 10px 10px #ccc;
            border-radius:10px;
            background:#fff;
            border:1px solid lightgray;
        }
        div>p{
            line-height: 28px;
            height: 28px;
        }
        input,button{
            height:28px;
        }
        input{
            padding-left: 20px;
        }
    </style>
</head>
<body>
<div>
    <h3>用户登录</h3>
    <p>用户: <input type="email" name="email" ></p>
    <p>密码: <input type="password" name="password" ></p>
    <p><button type="button">登录</button></p><p id="loading"></p>
</div>
<script>
    let btn = document.getElementsByTagName("button")[0];
    btn.onclick = function (){
        // 先对表单进行判断
        let email = document.getElementsByName('email')[0];
        let pass = document.getElementsByName('password')[0];
        if(email.value === ''){
            alert('请输入用户名');
            email.focus();
            return false;
        }else if(pass.value === ''){
            alert('请输入密码');
            pass.focus();
            return false;
        }


        //1.创建对象
        let xhr = new XMLHttpRequest();
        //2.监听响应状态
        xhr.onreadystatechange = function (){
            if(xhr.readyState !== 4 || xhr.status !== 200){
                //判断是否获取到数据
                let loading = document.createElement('img');
                loading.src = 'inc/loading.gif';
                loading.style = 'width:40px;height:40px;float:left;';
                let countload = document.getElementsByTagName('img');
                if(countload.length < 1){
                document.getElementById('loading').appendChild(loading);
                }
            }else{
                //生成返回数据
                let p = document.createElement('p');
                p.style.color = 'red';
                //将服务器返回的json字符串转为js对象
                let jsondata = JSON.parse(xhr.responseText);

                /*if(jsondata.status === 1){
                    p.innerHTML = jsondata.msg;
                }else if (jsondata.status ===0){
                    p.innerHTML = jsondata.msg;
                }*/

                p.innerHTML = jsondata.msg;
                rmload = document.getElementById('loading');
                setTimeout(function () {
                    document.getElementsByTagName('div')[0].removeChild(rmload);
                    document.getElementsByTagName('div')[0].appendChild(p);
                    if (jsondata.status == 1) {
                        alert('确认跳转');
                        location.href = 'admin.php';
                    }
                },2000);


            }
        }
        //3.设置请求参数
        xhr.open('post','inc/cheak.php',true);

        //4.设置请求头信息
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')


        //5.发送请求
        let data = {
            email:document.getElementsByName('email')[0].value,
            password:document.getElementsByName('password')[0].value
        };
        data_json = JSON.stringify(data);
        xhr.send('data=' + data_json);  //将数据变为数组传递
        btn.disabled = true;

    }

</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

cheak.php

<?php
/**
 * 验证登陆
 */
//print_r($_POST);
//echo $_POST['data'];
$user = json_decode($_POST['data']);
$email = $user->email;
$password = sha1($user->password);

//验证数据库中的数据
$pdo  = new PDO('mysql:host=127.0.0.1;dbname=php','root','admin');

$sql  = "SELECT COUNT(*) FROM `user` WHERE `email`='{$email}' AND `password`='{$password}'";

$stmt = $pdo->prepare($sql);
$stmt->execute();
if($stmt->fetchColumn(0) == 1){
    echo json_encode(['status'=>'1','msg'=>'登陆成功,跳转中...']);
}else{
    echo json_encode(['status'=>'0','msg'=>'用户名或密码错误...']);
}

三.Ajax运行流程

微信图片_20180916143545.jpg
Ajax运行流程demo ,GET方式提交实例;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>美文阅读</button>
<script>
    let btn = document.getElementsByTagName('button')[0];
    btn.onclick = function (){
        // 1.创建XHR对象
        let xhr = new XMLHttpRequest();
        //2.监听响应状态
        xhr.onreadystatechange = function(){
            if (xhr.readyState ===4){
                //判断是否获取到了响应数据
                if (xhr.status === 200){
                    let div = document.createElement('div');
                    div.style.width = '500px';
                    div.style.height = '600px;';
                    div.innerHTML = xhr.responseText;  //xhr.responseText 从服务器上取回的数据
                    //将新元素,也就是获取到的内容插入到页面中

                    document.body.appendChild(div);
                }else{
                    alert('响应失败'+xhr.status);
                }
            }else{
                //http请求正在继续,此处可放一个gif图
            }

        }
        //3.设置请求参数
        xhr.open('get','demo2.html',true);
        //4.发送请求
        xhr.send(null);
        btn.disabled = true;
    }
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

360截图20180916144619398.jpg
点击按钮后的效果图!

总结:详细了解Ajax的工作原理,通过POST提供数据是需要设置setRequestHeader  请求头信息,否则提交不了数据.



Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post