异步请求库开源算法

简单易用的异步请求操作库,统一调配接口

实例化

ajax(config)

配置参数说明
参数 示例 描述
baseURL location.origin 请求的根域
method 'GET' 请求方法:GET、POST、OPTIONS等
url '' 请求地址,默认为请求的根域(未带http协议头)
data null 提交的参数数据
headers null 修改提交时的请求头
crossDomain false 是否跨域
withCredentials false 是否携带凭证
cache true 是否设置缓存
responseType 'json' 响应数据类型
timeout 5000 请求超时时间
jsonp 'callback' jsonp回调函数引用
jsonpCallback 'jsonp_XXXX' jsonp回调函数名称
dataFormatter null 数据格式化处理
onTimeout function(){} 超时处理
// 直接发起请求 ajax({ url:'/api/getUser/', data:{ id:123456 } }).then(function(json){ // 回调处理 });

创建实例

ajax.create(config)

通过实例可以设置基础规则,统一对系列接口进行请求

// 设置实例基础配置 const instance = ajax.create({ baseURL:'https://passer-by.com/', crossDomain: true, withCredentials:true, headers:{ ticket:'XXXXXX' } }); instance.get('/api/getUser/',{ id:123456 }).then(function(json){ // 回调处理 });

拦截器

instance.interceptors

设置请求拦截器

const instance = ajax.create(); instance.interceptors.request.add(function(config){ return { headers:{ ticket:'XXXXXX', ...config.headers }, ...config }; });

设置响应拦截器

const instance = ajax.create(); instance.interceptors.response.add(function(data){ return { timestamp: new Date(data.time).getTime(), ...data }; });

通用请求

ajax.request(config)

// 等效于 ajax(config) ajax.request({ url:'/api/getUser/', data:{ id:123456 } }).then(function(json){ // 回调处理 });

GET请求

ajax.get(url,data,config)

ajax.get('/api/getNews/').then(function(json){ // 回调处理 });

POST请求

ajax.post(url,data,config)

ajax.post('/api/getUser/',{ id: '123456' }).then(function(json){ // 回调处理 });

PUSH请求

ajax.push(url,data,config)

ajax.push('/api/updateInfo/',{ id: '123456' }).then(function(json){ // 回调处理 });

PATCH请求

ajax.patch(url,data,config)

ajax.patch('/api/updateInfo/',{ id: '123456' }).then(function(json){ // 回调处理 });

DELETE请求

ajax.delete(url,config)

ajax.delete('/api/deleteInfo/').then(function(json){ // 回调处理 });

OPTIONS请求

ajax.options(url,config)

ajax.options('/api/deleteInfo/').then(function(json){ // 回调处理 });

JSONP请求

ajax.jsonp(url,data,config)

ajax.jsonp('https://outside.com/api/getInfo/').then(function(json){ // 回调处理 });

SSE连接

ajax.createEventSource(url,data,config)

// 创建SSE连接 const sse = ajax.createEventSource('https://outside.com/api/getInfo/'); sse.addEventListener('message',function(){ // 消息处理 });
算法开源

算法基于「MIT许可协议」开源,除需在源码中保留版权信息和许可声明外,你有权利使用、复制、修改、合并、出版发行、散布、再授权及贩售软件及软件的副本。数据持续更新中,如发现错漏或有想法建议可在此 反馈问题


响应式数据本地储存脚本:

https://passer-by.com/ajax/dist/ajax.min.js

Copyright © passer-by.com