1.0.1 • Published 5 years ago

simple-ajax-with-promise v1.0.1

Weekly downloads
10
License
ISC
Repository
github
Last release
5 years ago

Simple Ajax Promise - Ajaxp

使用Promise封装的轻量化ajax库

A light lib of ajax using Promise


安装

使用标签 下载 dist/ajaxp.min.js 在头部引入

<script src="ajaxp.min.js"></script>

使用npm

npm install simple-ajax-with-promise

使用ajaxp

  • ajax(config)

interface config

参数默认值类型说明
method'GET'String请求方法,目前支持POST和GET
url""String请求地址
data{}Object请求数据
asynctrueBoolean是否为异步
timeout0Number超时时间
ajaxp({
  url: 'http://example.com/xxxx',
  method: 'GET',
  data: {
    'name': 'Ajaxp'
  },
  timeout: 0,
  async: true,
}).then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
})

静态方法

Example

使用GET

ajaxp.get('http://example.com/xxx').then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
})

使用POST

ajaxp.post('http://example.com/xxx', {
  firstname: 'foo',
  lastname: 'bar'
})then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
}

创建实例

let instance = ajaxp.create(config)

interface config 在静态方法的基础上新增baseURL参数

参数默认值类型说明
baseURL""String请求的根地址,在此后的方法调用会在此地址上进行
method'GET'String请求方法,目前支持POST和GET
url""String请求地址
data{}Object请求数据
asynctrueBoolean是否为异步
timeout0Number超时时间

实例方法
此部分的config会覆盖掉instance的config

Example

let instance = ajaxp.create({
  baseURL: 'http://example.com/',
  method: 'delete'
})

// get请求
instance.get('xxx').then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
})

// post请求
instance.post('xxx', {
  firstname: 'foo',
  lastname: 'bar'
})then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
}

// request方法,使用config.method中的请求方法
instance.request('xxx').then((res) => {
  console.log(res.data)
}, (error) => {
  console.log(error)
}