zoukankan      html  css  js  c++  java
  • Ajax基础原理与应用

    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.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;
  • 相关阅读:
    跃迁方法论 Continuous practice
    EPI online zoom session 面试算法基础知识直播分享
    台州 OJ 2648 小希的迷宫
    洛谷 P1074 靶形数独
    洛谷 P1433 DP 状态压缩
    台州 OJ FatMouse and Cheese 深搜 记忆化搜索
    台州 OJ 2676 Tree of Tree 树状 DP
    台州 OJ 2537 Charlie's Change 多重背包 二进制优化 路径记录
    台州 OJ 2378 Tug of War
    台州 OJ 2850 Key Task BFS
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12190493.html
Copyright © 2011-2022 走看看