欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ajax基础原理与应用

程序员文章站 2024-02-01 11:05:46
Ajax函数封装ajax.js // Get / Post // 参数 get post // 是否异步 // 如何处理响应数据 // URL // var handleResponse = function(response) { // // } // ajax.get('demo1.php', ......

ajax函数封装ajax.js

// get / post
// 参数 get post
// 是否异步
// 如何处理响应数据
// url

// var handleresponse = function(response) {
//
// }
// ajax.get('demo1.php', 'name=zhangsan&age=20', handleresponse, true)
// ajax.post('demo1.php', 'name=zhangsan&age=20', handleresponse, true)
function ajax()
{
    // 初始化方法
    this.init = function()
    {
        this.xhr = new xmlhttprequest();
    };

    // get请求方法
    this.get = function(url, parameters, callback, async = true)
    {
        this.init();
        if (async) {
            // 异步请求
            this.xhr.onreadystatechange = function() {
                // this => this.xhr
                if (this.readystate == 4 && this.status == 200) {
                    callback(this.responsetext);
                }
            }
        }
        this.xhr.open('get', url + '?' + parameters, async);
        this.xhr.send();
    };

    // post请求方法
    this.post = function(url, parameters, callback, async = true)
    {
        this.init();
        if (async) {
            // 异步请求
            this.xhr.onreadystatechange = function ()
            {
                if (this.readystate == 4 && this.status == 200) {
                    callback(this.responsetext);
                }
            }
        }
        this.xhr.open('post', url, async);
        this.xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');
        this.xhr.send(parameters);
    }
}

var ajax = new ajax();

调用演示

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>title</title>
</head>
<body>
    <button id="btn">请求</button>
    <div id="container"></div>
    <script src="ajax.js"></script>
    <script>
        var btn = document.getelementbyid('btn');
        var container = document.getelementbyid('container');
        btn.onclick = function() {
                ajax.post('demo2.php', 'name=zhangsan&age=20', function(data) {
            container.innerhtml = data;
                });
        }
    </script>
</body>
</html>

ajax类封装ajax2.0.js

// 通过class定义类
class ajax
{
    // 构造方法
    constructor()
    {
        this.xhr = new xmlhttprequest()
    }

    // 内部方法,不加function
    get(url, parameters, callback, async = true)
    {
        if (async) {
            this.xhr.onreadystatechange = () => {
                if (this.xhr.readystate == 4 && this.xhr.status == 200) {
                    callback(this.xhr.responsetext)
                }
            }
            // this.xhr.onreadystatechange = function() {
            //     if (this.readystate == 4 && this.status == 200) {
            //         callback(this.responsetext)
            //     }
            // }
        }
        this.xhr.open('get', url + '?' + parameters, async)
        this.xhr.send()
    }

    // 内部方法,不加function
    post(url, parameters, callback, async = true)
    {
        if (async) {
            this.xhr.onreadystatechange = () => {
                if (this.xhr.readystate == 4 && this.xhr.status == 200) {
                    callback(this.xhr.responsetext)
                }
            }
            // this.xhr.onreadystatechange = function() {
            //     if (this.readystate == 4 && this.status == 200) {
            //         callback(this.responsetext)
            //     }
            // }
        }
        this.xhr.open('post', url, async)
        this.xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded')
        this.xhr.send(parameters)
    }

}

let ajax = new ajax()

调用演示

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>title</title>
</head>
<body>
<script src="ajax2.0.js"></script>
<script>
    ajax.get('demo1.php', 'course=ajax', function(data) {
        console.log(data)
    })
</script>
</body>
</html>

ajax方式实现分页

带搜索功能

Ajax基础原理与应用

Ajax基础原理与应用

首先是ajax类的封装ajax.js

let $ = new class {

    constructor()
    {
        this.xhr = new xmlhttprequest();
        this.xhr.onreadystatechange = () => {
            if (this.xhr.readystate == 4 && this.xhr.status == 200) {
                // process response text
                let response = this.xhr.responsetext;
                if (this.type == "json") {
                    response = json.parse(response);
                }
                this.callback(response);
            }
        }
    }

    get(url, parameters, callback, type = "text")
    {
        // url = test.php?username=zhangsan&age=20
        // parameters = {"username": "zhangsan", "age": 20}
        let data = this.parseparameters(parameters);
        if (data.length > 0) {
            url += "?" + data;
        }
        this.type = type;
        this.callback = callback;
        this.xhr.open("get", url, true);
        this.xhr.send();
    }

    post(url, parameters, callback, type = "text")
    {
        let data = this.parseparameters(parameters);
        this.type = type;
        this.callback = callback;
        this.xhr.open("post", url, true);
        this.xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");
        this.xhr.send(data);
    }

    parseparameters(parameters)
    {
        // username=zhangsan&age=20
        let buildstr = "";
        for (let key in parameters) {
            let str = key + "=" + parameters[key];
            buildstr += str + "&";
        }
        return buildstr.substring(0, buildstr.length - 1);
    }
};

前端页面

<!doctype html>
<html lang="en">
<head>
    <!-- required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- bootstrap css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-gn5384xqq1aowxa+058rxpxpg6fy4iwvtnh0e263xmfcjlsawiggfaw/dais6jxm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>test users</title>
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">users list</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsupportedcontent" aria-controls="navbarsupportedcontent" aria-expanded="false" aria-label="toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarsupportedcontent">
                <ul class="navbar-nav mr-auto"></ul>
                <form class="form-inline my-2 my-lg-0" onsubmit="return false;">
                    <input class="form-control mr-sm-2 keywords" type="search" placeholder="search" aria-label="search" value="">
                    <button class="btn btn-outline-success my-2 my-sm-0 searchbtn" type="submit">search</button>
                </form>
            </div>
        </nav>
    </header>

    <!-- data -->
    <div class="container" style="margin-top: 10px">
        <h2>test users</h2>
        <table class="table table-striped">
            <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">username</th>
                <th scope="col">age</th>
                <th scope="col">gender</th>
                <th scope="col">phone</th>
                <th scope="col">address</th>
                <th scope="col">created_at</th>
            </tr>
            </thead>
            <tbody></tbody>
        </table>
        <!-- pagination-->
        <nav aria-label="page navigation example">
            <ul class="pagination"></ul>
        </nav>
    </div>


<!-- optional javascript -->
<!-- jquery first, then popper.js, then bootstrap js -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-kj3o2dktikvyik3uenzmm7kckrr/re9/qpg6aazgjwfdmvna/gpgff93hxpg5kkn" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-apnbgh9b+y1qktv3rn7w3mgpxhu9k/scqsap7huibx39j7fakfpskvxusvfa0b4q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-jzr6spejh4u02d8jot6vlehfe/jqgirrsqqxsffwpi1mquvdayjuar5+76pvcmyl" crossorigin="anonymous"></script>
<script src="../library/ajax.js"></script>
<script>
    let pageno = 1;
    let kws = '';
    let searchbtn = document.getelementsbyclassname('searchbtn')[0];
    searchbtn.onclick = function() {
        let search = document.getelementsbyclassname('keywords')[0];
        let keywords = search.value;
        requestdata(pageno, keywords);
        kws = keywords;
    };

    let requestpage = function(page) {
        requestdata(page, kws);
        pageno = page;
    };

    let requestdata = function(page_number, keywords) {
        let pagination = document.getelementsbyclassname('pagination')[0];
        let tbody = document.getelementsbytagname('tbody')[0];
        tbody.innerhtml = '<tr><td colspan="7" class="text-center"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i> 加载中...</td></tr>'
        $.get('users.php', {"page": page_number, "keywords": keywords}, function (res) {
            let trs = '';
            if (res.code == 1) {
                // 请求成功
                res.rows.foreach(function (item) {
                    let tr = '<tr><th scope="row">' + item.id + '</th>' +
                        '<td>' + item.username + '</td>' +
                        '<td>' + item.age + '</td>' +
                        '<td>' + item.gender + '</td>' +
                        '<td>' + item.phone + '</td>' +
                        '<td>' + item.address + '</td>' +
                        '<td>' + item.created_at + '</td>' +
                        '</tr>';
                    trs += tr;
                });
                tbody.innerhtml = trs;

                // 加载页码导航
                // previous
                let previousbtn = '';
                if (res.page_number == 1) {
                    previousbtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestpage(' + (res.page_number - 1) + ');">previous</a></li>';
                } else {
                    previousbtn = '<li class="page-item"><a class="page-link" href="javascript:requestpage(' + (res.page_number - 1) + ');">previous</a></li>';
                }
                // next
                let nextbtn = '';
                if (res.page_total == res.page_number) {
                    nextbtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestpage(' + (res.page_number + 1) + ');">next</a></li>';
                } else {
                    nextbtn = '<li class="page-item"><a class="page-link" href="javascript:requestpage(' + (res.page_number + 1) + ');">next</a></li>'
                }

                let pages = previousbtn;
                for (let page = 1; page <= res.page_total; page++) {
                    let active = '';
                    if (page == res.page_number) {
                        active = 'active';
                    }
                    pages += '<li class="page-item ' + active + '"><a class="page-link" href="javascript:requestpage(' + page + ');">' + page + '</a></li>';
                }
                pages += nextbtn;
                pagination.innerhtml = pages;
            }
        }, 'json');
    };
    requestdata(1, '');
</script>
</body>
</html>

users.php

<?php
/**
 * created by phpstorm.
 * user: jasonlee
 * date: 2018/12/1
 * time: 18:27
 */
// 请求数据库,响应对应页码的数据
// pdo

// 接收请求数据
$pageno = $_get['page'] ?? 1;
$pagesize = 5;

// 接收查询参数
$keywords = $_get['keywords'] ?? '';

// 1 -- 0
// 2 -- 5
// 3 -- 10


$data = [];
try {
    $pdo = new pdo('mysql:host=localhost:3306;dbname=test_ajax_pager',
        'root',
        '123456',
        [pdo::attr_errmode => pdo::errmode_exception]
    );

    // 请求mysql 查询记录总数
    $sql = 'select count(*) as aggregate from test_users';
    if (strlen($keywords) > 0) {
        $sql .= ' where username like ?';
    }
    $stmt = $pdo->prepare($sql);
    if (strlen($keywords) > 0) {
        $stmt->bindvalue(1, '%' . $keywords . '%', pdo::param_str);
    }
    $stmt->execute();
    $total = $stmt->fetch(pdo::fetch_assoc)['aggregate'];

    // 计算最大页码,设置页码边界
    $minpage = 1;
    $maxpage = ceil($total / $pagesize); // 3.6
    $pageno = max($pageno, $minpage);
    $pageno = min($pageno, $maxpage);
    $offset = ($pageno - 1) * $pagesize;

    $sql = 'select id, username, age, gender, phone, address, created_at from test_users';
    if (strlen($keywords) > 0) {
        $sql .= ' where username like ?';
    }
    $sql .= ' limit ?, ?';
    $stmt = $pdo->prepare($sql);
    if (strlen($keywords) > 0) {
        $stmt->bindvalue(1, '%' . $keywords . '%', pdo::param_str);
        $stmt->bindvalue(2, (int)$offset, pdo::param_int);
        $stmt->bindvalue(3, (int)$pagesize, pdo::param_int);
    } else {
        $stmt->bindvalue(1, (int)$offset, pdo::param_int);
        $stmt->bindvalue(2, (int)$pagesize, pdo::param_int);
    }
    $stmt->execute();
    $results = $stmt->fetchall(pdo::fetch_assoc);
    $data = [
        'code' => 1,
        'msg' => 'ok',
        'rows' => $results,
        'total_records' => (int)$total,
        'page_number' => (int)$pageno,
        'page_size' => (int)$pagesize,
        'page_total' => (int)$maxpage,
    ];

} catch (pdoexception $e) {
    $data = [
        'code' => 0,
        'msg' => $e->getmessage(),
        'rows' => [],
        'total_records' => 0,
        'page_number' => 0,
        'page_size' => (int)$pagesize,
        'page_total' => 0,
    ];
}

header('content-type: application/json');
echo json_encode($data);

数据库结构test_ajax_pager.sql

/*
 navicat mysql data transfer

 source server         : 127.0.0.1
 source server type    : mysql
 source server version : 80012
 source host           : localhost:3306
 source schema         : test_ajax_pager

 target server type    : mysql
 target server version : 80012
 file encoding         : 65001

 date: 18/11/2018 10:56:13
*/

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for test_users
-- ----------------------------
drop table if exists `test_users`;
create table `test_users` (
  `id` int(10) unsigned not null auto_increment,
  `username` varchar(50) not null default '',
  `age` tinyint(4) not null default '1',
  `gender` varchar(30) not null default 'not specified',
  `phone` varchar(50) not null default '',
  `address` varchar(255) not null default '',
  `created_at` datetime not null default current_timestamp,
  primary key (`id`)
) engine=innodb auto_increment=20 default charset=utf8;

-- ----------------------------
-- records of test_users
-- ----------------------------
begin;
insert into `test_users` values (1, 'zhangsan', 20, 'male', '13888888888', 'chaoyang beijing', '2018-11-18 09:52:23');
insert into `test_users` values (2, 'lisi', 30, 'female', '13899999999', 'haidian beijing', '2018-11-18 09:53:30');
insert into `test_users` values (3, 'wangwu', 32, 'male', '13877777777', 'changping beijing', '2018-11-18 09:54:15');
insert into `test_users` values (4, 'zhaoliu', 28, 'male', '13866666666', 'shunyi beijing', '2018-11-18 09:54:34');
insert into `test_users` values (5, 'tianqi', 23, 'not specified', '13855555555', 'changping beijing', '2018-11-18 09:55:18');
insert into `test_users` values (6, 'liba', 33, 'female', '13844444444', 'chaoyang beijing', '2018-11-18 09:55:53');
insert into `test_users` values (7, 'wangjiu', 45, 'not specified', '13833333333', 'hongkou shanghai', '2018-11-18 09:56:21');
insert into `test_users` values (8, 'wanger', 26, 'male', '13777777777', 'hangzhou', '2018-11-18 09:57:10');
insert into `test_users` values (9, 'liyi', 25, 'not specified', '13555555555', 'shanghai', '2018-11-18 09:58:38');
insert into `test_users` values (10, 'zhangxiaosan', 21, 'not specified', '13111111111', 'beijing', '2018-11-18 09:59:09');
insert into `test_users` values (11, 'lixiaosi', 32, 'male', '13222222222', 'shanghai', '2018-11-18 09:59:30');
insert into `test_users` values (12, 'wangxiaowu', 33, 'not specified', '13812345678', 'beijing', '2018-11-18 10:01:44');
insert into `test_users` values (13, 'zhaoxiaoliu', 44, 'not specified', '13612345678', 'shanghai', '2018-11-18 10:02:10');
insert into `test_users` values (14, 'tianxiaoqi', 52, 'female', '18612345678', 'beijing', '2018-11-18 10:02:35');
insert into `test_users` values (15, 'lixiaoba', 36, 'not specified', '18712345678', 'shanghai', '2018-11-18 10:02:57');
insert into `test_users` values (16, 'wangxiaojiu', 42, 'not specified', '18212345678', 'hangzhou', '2018-11-18 10:03:23');
insert into `test_users` values (17, 'wangxiaoer', 31, 'male', '18512345678', 'suzhou', '2018-11-18 10:03:51');
insert into `test_users` values (18, 'lixiaoyi', 28, 'female', '18787654321', 'guangzhou', '2018-11-18 10:04:22');
commit;

set foreign_key_checks = 1;