原生Ajax函数
2024-09-24 06:41:35
前言
在日常工作中,我经常使用Jquery的Ajax来获取接口数据。这几天有一个的官网要制作,由于网站比较小,有一些与服务器通信的接口处理,并没有涉及到复杂的交互功能。为了可以减少加载Jquery库的时间,也不用负担Jquery复杂的逻辑处理带来的性能消耗。我决定不使用jquery,自己写了一个原生的Ajax函数。
需求整理
一般来说,前端与服务器的通信是使用XHR对象的。我做的官网是有几个异域的接口,然而XHR对象是没有跨域功能的。所以我把JSONP整合进来。
接下来,我们来看看整体功能图:
流程图
输入参数
首先,我们定义一个Ajax函数,并设置了一些输入参数。
1 |
function ajax(options){ var url = options.url || "", //请求的链接 |
参数表:
参数 | 默认值 | 描述 | 可选值 |
---|---|---|---|
url | “” | 请求的链接 | string |
type | get | 请求的方法 | get,post |
data | null | 请求的数据 | object,string |
contentType | “” | 请求头 | string |
dataType | “” | 请求的类型 | jsonp |
async | true | 是否异步 | blooean |
timeOut | undefined | 超时时间 | number |
before | function(){} | 发送之前执行的函数 | function |
error | function(){} | 请求报错执行的函数 | function |
success | function(){} | 请求成功的回调函数 | function |
编码
一般来说,发送到后端的数据,若是包括中文或某些标点符号时,就要对发送的数据进行编码了。
- 如果data为字符串,通过&分割,对键名与键值分别编码
- 如果data为对象,把键值转化为字符串,再进行编码
- 由于encodeURIComponent不对+编码,所以我们用replace方法手动编码
- 若是使用get方法或JSONP,则数据是通过URL参数的方法传到后台,所以我们手动添加数据到URL
1 |
//编码数据 |
XMLHttpRequerst
- 创建XHR对象,并针对IE进行兼容性处理
- 调用XHR的open方法,设置请求的方法,请求的链接,是否异步
- 设置请求头
- 添加监听,如果成功则执行success函数,报错则执行error函数
- 调用XHR的send方法,发送数据。如果是get方法,我们已经通过setData方法把数据添加到URL中了,所以这里data设置为null
1 |
function createXHR() { |
JSONP
- 创建script标签
- 设置回调函数名称
- 监听回调函数
- 设置URL,并添加到文档中
1 |
// 创建JSONP |
超时设置
- 设置一个全局的定时器标识,用来在回调函数中清除定时器
- JSONP
- 传入两个参数,一个是回调函数名,一个是script标签
- 超时之后,移除监听函数,移除script标签
- XHR
- 超时之后,调用XHR的abort方法,停止请求
- 由于执行abort()方法后,有可能触发onreadystatechange事件,所以设置一个timeout_bool标识,来忽略中止触发的事件。
1 |
var timeout_flag = null, //定时器标识 |
添加超时函数,并设置在回调成功后移除定时器
JSONP
1 |
// 创建JSONP |
XHR
function createXHR() {
……
//添加监听
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (timeOut !== undefined) {
//由于执行abort()方法后,有可能触发onreadystatechange事件,
//所以设置一个timeout_bool标识,来忽略中止触发的事件。
if (timeout_bool) {
return;
}
clearTimeout(timeout_flag);
}
……
}
};
//发送请求
xhr.send(type === "get" ? null : data);
setTime(); //请求超时
}
全部代码
1 |
function ajax(options) { |
源码下载
源码放在github中了。欢迎下载,地址
本文摘自:littleBlack
最新文章
- 设计模式--观察者模式初探和java Observable模式
- WebApi 通过类名获取类并实例化
- Linux安装SmartSVN及破解
- [UOJ#34]多项式乘法
- shell中的双引号,单引号,反引号
- 关于android app两次点击返回键退出的处理
- 在LINUX终端和VIM下复制粘贴
- JS线程模型&;Web Worker
- Comet学习资料
- DataTable去除重复行
- atitit..主流 浏览器 js 发动机 内核 市场份额 attialx总结vOa9
- linux kernel module
- Java Web 错误排查
- Spring--AOP--面向切面编程
- 如何把遗留的Java应用托管在Service Fabric中
- windows下安装mysql数据库修改端口号
- CentOS No package nginx available.
- 通过身份证分析出生年月日、性别、年龄的SQL语句
- 001-Spring的设计理念和整体架构
- leetcode112
热门文章
- ipa包兼容性大作战!WeTest iOS深度兼容测试全新升级
- TensorFlow Python3.7环境下的源码编译(一)环境准备
- 来源自rnnoise,但非rnn
- .NET处理Json的几种方式
- Netty源码分析第1章(Netty启动流程)---->;第4节: 注册多路复用
- 【LDAP安装】在已编译安装的PHP环境下安装LDAP模块
- Git----01介绍&;下载&;安装&;创建本地仓库
- [shell] bash数组(for时排序)
- Daily Scrum (2015/11/6)
- 《Spring1之 第一次站立会议(重发)》