Ajax基础原理与应用

前端之家收集整理的这篇文章主要介绍了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',true)
function Ajax()
{
     初始化方法
    this.init = ()
    {
        this.xhr = new XMLHttpRequest();
    };

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

     post请求方法
    this.post =  ()
            {
                this.xhr.open('POST',url,1)">this.xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        .xhr.send(parameters);
    }
}

var ajax = new Ajax();

调用演示

<!DOCTYPE html>
<html lang="en"head>
    Meta charset="UTF-8"title>Title</bodybutton id="btn">请求buttondiv ="container"></divscript src="ajax.js"script>
        var btn = document.getElementById('btn);
         container container);
        btn.onclick = function() {
                ajax.post(demo2.PHPname=zhangsan&age=20(data) {
            container.innerHTML  data;
                });
        }
    html>

Ajax类封装ajax2.0.js

 通过class定义类
class Ajax
{
     构造方法
    constructor()
    {
         XMLHttpRequest()
    }

     内部方法,不加function
    get(url,1)">this.xhr.onreadystatechange = () => {
                this.xhr.readyState == 4 && this.xhr.status == 200.xhr.responseText)
                }
            }
             this.xhr.onreadystatechange = function() {
                 if (this.readyState == 4 && this.status == 200) {
                     callback(this.responseText)
                 }
             }
        }
        .xhr.send()
    }

     内部方法,不加function
    post(url,1)">)
        .xhr.send(parameters)
    }

}

let ajax = new Ajax()

调用演示

="ajax2.0.js">
    ajax.get(demo1.PHPcourse=ajax(data) {
        console.log(data)
    })
>

Ajax方式实现分页

搜索功能

首先是ajax类的封装Ajax.js

let $ =  class {

    constructor()
    {
         XMLHttpRequest();
         {
            ) {
                 process response text
                let response = .xhr.responseText;
                this.type == "json") {
                    response = JSON.parse(response);
                }
                .callback(response);
            }
        }
    }

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

    post(url,1)">)
    {
        let data = this.xhr.open("POST",1)">this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded".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<!-- required Meta tags -->
    ="utf-8"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"="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">test Usersheader>
        nav class="navbar navbar-expand-lg navbar-light bg-light">
            a ="navbar-brand"="#">Users Lista="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                span ="navbar-toggler-icon"span>

            ="collapse navbar-collapse" id="navbarSupportedContent"ul ="navbar-nav mr-auto"ulform ="form-inline my-2 my-lg-0" onsubmit="return false;">
                    input ="form-control mr-sm-2 keywords"="search" placeholder="Search" value=""="btn btn-outline-success my-2 my-sm-0 searchBtn"="submit">Searchformnav data ="container" style="margin-top: 10px"h2table ="table table-striped"theadtrth scope="col">#th>Username>Age>Gender>Phone>Address>Created_attbodytable Pagination-->
        aria-label="Page navigation example"="pagination">


 Optional JavaScript -->
 jQuery first,then Popper.js,then Bootstrap JS ="https://code.jquery.com/jquery-3.2.1.slim.min.js"="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"="../library/Ajax.js"
    let pageNo 1;
    let kws '';
    let searchBtn  document.getElementsByClassName(searchBtn)[0];
    searchBtn.onclick () {
        let search keywords];
        let keywords  search.value;
        requestData(pageNo,keywords);
        kws  keywords;
    };

    let requestPage (page) {
        requestData(page,kws);
        pageNo  page;
    };

    let requestData (page_number,keywords) {
        let pagination pagination];
        let tbody  document.getElementsByTagName(tbody];
        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,1)">: keywords},1)"> (res) {
            let trs ;
            if (res.code == ) {
                // 请求成功
                res.rows.forEach( (item) {
                    let tr <tr><th scope="row">' + item.id + </th>+
                        <td> item.username </td> item.age  item.gender  item.phone  item.address  item.created_at </tr>;
                    trs += tr;
                });
                tbody.innerHTML  trs;

                 加载页码导航
                 prevIoUs
                let prevIoUsBtn ;
                 (res.page_number ) {
                    prevIoUsBtn <li class="page-item disabled"><a class="page-link" href="javascript:requestPage(- ) );">PrevIoUs</a></li>;
                } else {
                    prevIoUsBtn <li class="page-item"><a class="page-link" href="javascript:requestPage(;
                }
                 next
                let nextBtn  (res.page_total == res.page_number) {
                    nextBtn );">Next</a></li> {
                    nextBtn 
                }

                let pages  prevIoUsBtn;
                for (let page ; page <= res.page_total; page++) {
                    let active ;
                     (page  res.page_number) {
                        active active;
                    }
                    pages += <li class="page-item  active "><a class="page-link" href="javascript:requestPage( page );"></a></li>;
                }
                pages  nextBtn;
                pagination.innerHTML  pages;
            }
        },1)">json);
    };
    requestData();
>

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',1)">
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

     请求MysqL 查询记录总数
    $sql = 'SELECT count(*) AS aggregate FROM test_users';
    strlen($keywords) > 0) {
        $sql .= ' WHERE username like ?';
    }
    $stmt = $pdo->prepare($sql);
    $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);
    min($maxPage$offset = ($pageNo - 1) * $pageSize;

    $sql = 'SELECT id,username,age,gender,phone,address,created_at FROM test_users'$sql .= ' LIMIT ?,?'PARAM_STR);
        $stmt->bindValue(2,(int)$offset,1)">PARAM_INT);
        $stmt->bindValue(3,1)">$pageSize,1)">PARAM_INT);
    } else {
        PARAM_INT);
    }
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
     [
        'code' => 1,'msg' => 'ok','rows' => $results,'total_records' => (int)$total,'page_number' => (int)$maxPage,1)">
    ];

} catch (PDOException $e) {
     [
        'code' => 0,'msg' => $e->getMessage(),'rows' => [],'total_records' => 0,'page_number' => 0,'page_total' => 0,1)">
    ];
}

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) NULL DEFAULT ''tinyint(4) '1'30) Not Specified255) datetime CURRENT_TIMESTAMPPRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

 Records of test_usersBEGIN;
INSERT INTO `test_users` VALUES (1,zhangsan',1); font-weight: bold">20,1)">Male13888888888Chaoyang Beijing2018-11-18 09:52:232,1)">lisi30,1)">Female13899999999Haidian Beijing2018-11-18 09:53:303,1)">wangwu32,1)">13877777777Changping Beijing2018-11-18 09:54:154,1)">zhaoliu28,1)">13866666666Shunyi Beijing2018-11-18 09:54:345,1)">tianqi23,1)">138555555552018-11-18 09:55:186,1)">liba33,1)">138444444442018-11-18 09:55:537,1)">wangjiu45,1)">13833333333Hongkou Shanghai2018-11-18 09:56:218,1)">wanger26,1)">13777777777Hangzhou2018-11-18 09:57:109,1)">liyi25,1)">13555555555Shanghai2018-11-18 09:58:3810,1)">zhangxiaosan21,1)">13111111111Beijing2018-11-18 09:59:0911,1)">lixiaosi132222222222018-11-18 09:59:3012,1)">wangxiaowu138123456782018-11-18 10:01:4413,1)">zhaoxiaoliu44,1)">136123456782018-11-18 10:02:1014,1)">tianxiaoqi52,1)">186123456782018-11-18 10:02:3515,1)">lixiaoba36,1)">187123456782018-11-18 10:02:5716,1)">wangxiaojiu42,1)">182123456782018-11-18 10:03:2317,1)">wangxiaoer31,1)">18512345678Suzhou2018-11-18 10:03:5118,1)">lixiaoyi18787654321Guangzhou2018-11-18 10:04:22COMMIT1;

猜你在找的Ajax相关文章