Blogger Information
Blog 43
fans 0
comment 0
visits 26993
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax技术+2018年9月16日
Lee的博客
Original
588 people have browsed it

Ajax的工作原理分析

AJax全称AsynchronousJavaScript and XML,一种创建交互式网页应用的网页开发技术,他的优点在于不刷新整个页面的情况下与服务器通信保持原有页面状态。

AJAX通过XMLHttpRequest对象来工作

对象XMLHttpRequest有一下几个属性

  1.  onreadyStatechange 调用一个javaScript函数 
    2. readyState 请求的状态: 
    0>.请求未初始化 
    1>.服务器链接已建立 
    2>.请求已接收 
    3>.请求处理中 
    4>.请求已完成,响应已就绪 
    3.responseText 返回请求数据文本 
    4.responseXML 返回XML文档对象 
    5.status 返回状态码 如404 200

Ajax的原理简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。


Ajax用户登录验证

实例

<?php
$user = json_decode($_POST['data']);

$email = $user->email;
$password = sha1($user->password);

$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
$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'=>'登录成功,正在跳转...']);
    exit;
}else{
    echo json_encode(['status'=>0,'msg'=>'邮箱或密码错误,登录失败!']);
    exit;
}

运行实例 »

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


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax表单</title>
</head>
<body>
<h3>用户登陆</h3>
<form action="">
    <p>邮箱:<input type="email" name="email"></p>
    <p>密码:<input type="password" name="password"></p>
    <p><button type="button">提交</button></p>
</form>
</body>
</html>
<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){
                    // 创建P元素
                    let p = document.createElement('p');
                    p.style.color = 'green';
                    // 响应成功,通过xhr对象的responseText属性可以获取响应的文本,此时是html文档内容
                    let json = JSON.parse(xhr.responseText);
                    if (json.status ===1){
                        p.innerHTML = json.msg;
                    } else if (json.status == 0){
                        p.innerHTML = json.msg;
                    }
                    // 将响应文本添加到新元素上
                    document.forms[0].appendChild(p);
                    btn.disabled = true;

                    setTimeout(function () {
                        document.forms[0].removeChild(p);
                        btn.disabled = false;
                        if (json.status == 1){
                            location.href = 'admin.php';
                        }
                    },3000);
                } else {
                    alert('响应失败'+xhr.status);
                }
            } else {

            }
        }
        //3.设置请求参数
        xhr.open('post','inc/check.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 = 'email='+data.email+'&password='+data.password;
        let data_json = JSON.stringify(data);
        xhr.send('data='+data_json);
    }
</script>

运行实例 »

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



实例

<?php
$user = json_decode($_POST['data']);

$email = $user->email;
$password = sha1($user->password);

$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
$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'=>'登录成功,正在跳转...']);
    exit;
}else{
    echo json_encode(['status'=>0,'msg'=>'邮箱或密码错误,登录失败!']);
    exit;
}

运行实例 »

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


QQ截图20180916212818.png

Ajax的完整运行流程(以get为例),共四步

P80916-182737(1).jpg


总结,AJAX非常好用,但是老师讲得有点复杂,不是很会用,要慢慢了解!

Correction status:Uncorrected

Teacher's comments:
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