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 '',
`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', '', 'Chaoyang Beijing', '2018-11-18 09:52:23');
INSERT INTO `test_users` VALUES (2, 'lisi', 30, 'Female', '', 'Haidian Beijing', '2018-11-18 09:53:30');
INSERT INTO `test_users` VALUES (3, 'wangwu', 32, 'Male', '', 'Changping Beijing', '2018-11-18 09:54:15');
INSERT INTO `test_users` VALUES (4, 'zhaoliu', 28, 'Male', '', 'Shunyi Beijing', '2018-11-18 09:54:34');
INSERT INTO `test_users` VALUES (5, 'tianqi', 23, 'Not Specified', '', 'Changping Beijing', '2018-11-18 09:55:18');
INSERT INTO `test_users` VALUES (6, 'liba', 33, 'Female', '', 'Chaoyang Beijing', '2018-11-18 09:55:53');
INSERT INTO `test_users` VALUES (7, 'wangjiu', 45, 'Not Specified', '', 'Hongkou Shanghai', '2018-11-18 09:56:21');
INSERT INTO `test_users` VALUES (8, 'wanger', 26, 'Male', '', 'Hangzhou', '2018-11-18 09:57:10');
INSERT INTO `test_users` VALUES (9, 'liyi', 25, 'Not Specified', '', 'Shanghai', '2018-11-18 09:58:38');
INSERT INTO `test_users` VALUES (10, 'zhangxiaosan', 21, 'Not Specified', '', 'Beijing', '2018-11-18 09:59:09');
INSERT INTO `test_users` VALUES (11, 'lixiaosi', 32, 'Male', '', 'Shanghai', '2018-11-18 09:59:30');
INSERT INTO `test_users` VALUES (12, 'wangxiaowu', 33, 'Not Specified', '', 'Beijing', '2018-11-18 10:01:44');
INSERT INTO `test_users` VALUES (13, 'zhaoxiaoliu', 44, 'Not Specified', '', 'Shanghai', '2018-11-18 10:02:10');
INSERT INTO `test_users` VALUES (14, 'tianxiaoqi', 52, 'Female', '', 'Beijing', '2018-11-18 10:02:35');
INSERT INTO `test_users` VALUES (15, 'lixiaoba', 36, 'Not Specified', '', 'Shanghai', '2018-11-18 10:02:57');
INSERT INTO `test_users` VALUES (16, 'wangxiaojiu', 42, 'Not Specified', '', 'Hangzhou', '2018-11-18 10:03:23');
INSERT INTO `test_users` VALUES (17, 'wangxiaoer', 31, 'Male', '', 'Suzhou', '2018-11-18 10:03:51');
INSERT INTO `test_users` VALUES (18, 'lixiaoyi', 28, 'Female', '', 'Guangzhou', '2018-11-18 10:04:22');
COMMIT; SET FOREIGN_KEY_CHECKS = 1;

Ajax基础原理与应用的更多相关文章

  1. 史上最全的Ajax基础详解

    同步请求和异步请求 先解释一下同步和异步的概念: 同步是指:发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式. 异步是指:发送方发出数据后,不等接收方发回响应,接着发送下个数据包的通讯 ...

  2. 【Java EE 学习 31】【JavaScript基础增强】【Ajax基础】【Json基础】

    一.JavaScript基础增强 1.弹窗 (1)使用window对象的showModelDialog方法和showModelessDialog方法分别可以弹出模式窗口和非模式窗口,但是只能在IE中使 ...

  3. Ajax基础2

    什么是服务器 网页浏览过程的分析 如何配置自己的服务器程序(AMP) 什么是Ajax 无刷新数据读取 异步,同步 Ajax基础(2) 使用Ajax 基础请求显示txt的文件 字符集编码 缓存,阻止缓存 ...

  4. Ajax基础--JavaScript实现

    ajax原理 1.ajax 即“Asynchronous JavaScript and XML”(异步 JavaScript 和 XML),也就是无刷新数据读取. 通俗地讲就是:AJAX 通过在后台与 ...

  5. Web前端-Ajax基础技术(下)

    Web前端-Ajax基础技术(下) 你要明白ajax是什么,怎么使用? ajax,web程序是将信息放入公共的服务器,让所有网络用户可以通过浏览器进行访问. 浏览器发送请求,获取服务器的数据: 地址栏 ...

  6. 第十三节 Ajax基础

    什么是服务器:简单地,可以说服务器就是一个内存超大的计算机,可以存放很多数据和文件(当然,如果不需要太多的数据存储量,我们也可以用电脑.手机等一系列小型计算机作为服务器,只不过性能的差别而已) 网页浏 ...

  7. APPcrawler基础原理解析及使用

    一.背景 一年前,我们一直在用monkey进行Android 的稳定性测试 ,主要目的就是为了测试app 是否会产生Crash,是否会有ANR,页面错误等问题,在monkey测试过程中,实现了脱离Ca ...

  8. php面试专题---13、AJAX基础内容考点

    php面试专题---13.AJAX基础内容考点 一.总结 一句话总结: ajax对提升用户速度,缓解服务器压力方面也是很有可取之处的,毕竟传递的数据少了 1.AJAX基础概念? Asynchronou ...

  9. PHP面试 AJAX基础内容

    AJAX基础内容 Ajax的基本工作原理 Ajax基础概念:通过在后台与服务器进行少量数据交换,Ajax可以使用网页实现异步更新 Ajax工作原理:XMLHttpRequest是Ajax的基础     ...

随机推荐

  1. Linux 服务器注意事项

    1.创建时  数据文件一定分盘挂载 2.LVM 虚拟磁盘卷是否创建    有争议??? 3.hosts 文件 最好添加本机映射          主机名  127.0.0.1      4.iptab ...

  2. Nginx-2.初学者使用

    原文 Nginx有一个master进程和几个worker进程.master进程用来读取和评估配置文件,以及维护worker进程.worker进程用来处理实际的请求.Nginx使用事件模型和基于操作系统 ...

  3. 【转载】s19文件格式详解

    来源:http://blog.csdn.net/xxxl/article/details/19494187 1.概述 为了在不同的计算机平台之间传输程序代码和数据,摩托罗拉将程序和数据文件以一种可打印 ...

  4. Vue使用Clipboard.JS在h5页面中复制内容

    安装clipboard.js github路径:https://github.com/zenorocha/clipboard.js 安装: npm install clipboard --save 引 ...

  5. zabbix-agent TIME_WAIT 过多(转)

    一.系统环境 操作系统: Centos 6.4 64bit zabbix-agent 版本: Zabbix agent v2.2.7 (revision 50148) (24 October 2014 ...

  6. JAVA架构之单点登录 任务调度 权限管理 性能优化大型项目实战

    单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户的一次登录能得到其他所有系统的信任.单点登录在大型网站里使用得 ...

  7. centos6.8 安装.net core2.1 sdk 或 .net core2.1 runtime

    前段时间看.net core 更更更新了,大家反应都挺好,想有机会也学习一下,正好这两天要写一个简单的服务在centos上面跑,于是决定放弃使用java,直接.net core走起来,事情进行的非常顺 ...

  8. JDK SPI 机制

    一.概述 最早看到 SPI 这个机制是在 dubbo 实现 中,最近发现原来也不是什么新东西,竟然就是 JDK 中内置的玩意,今天就来一探究竟,看看它到底是什么玩意! SPI的全称是 Service ...

  9. 从零构建Flink SQL计算平台 - 1平台搭建

    一.理想与现实 Apache Flink 是一个分布式流批一体化的开源平台.Flink 的核心是一个提供数据分发.通信以及自动容错的流计算引擎.Flink 在流计算之上构建批处理,并且原生的支持迭代计 ...

  10. 解决MySql客户端秒退(找不到my.ini)

    问题说明(环境:windows7,MySql8.0) 今天安装好MySql后启动MySql服务-->启动服务都失败的就不要往下看了,自行百度解决. 打开客户端秒退,但在cmd中是可以使用数据库的 ...