foreword
As the title, I encapsulated an own ajax request function.
Uncompressed version: https://cdn.xxhzm.cn/request/request.js
Compressed version: https://cdn.xxhzm.cn/request/request.min.js
Instructions for use
pass parameters
- URL address
- Request method (GET, POST)
- request parameter
- request header
- Whether to request asynchronously (true, false), asynchronous request is enabled by default
GET
GET takes no parameters and no request headers:
<script src="https://cdn.xxhzm.cn/request/request.min.js"></script> request('user/info', 'GET').then(val => { console.log(val) }).catch(val => { console.error(val) })
GET with parameters, without request headers:
const data = { username: 'xxhzm', sex: '男', age: '16' } request('user/info', 'GET', data).then(val => { console.log(val) }).catch(val => { console.error(val) })
GET without parameters, with request headers
const header = { 'Content-Type': 'text/html; charset=utf-8' } request('user/info', 'GET', null, header).then(val => { console.log(val) }).catch(val => { console.error(val) })
POST
post without parameters, without request headers
request('user/info', 'POST').then(val => { console.log(val) }).catch(val => { console.log(val) })
post with parameters, without request headers
const data = new URLSearchParams() data.append('name', 'xxhzm') data.append('sex', '男') data.append('age', '16') request('user/info', 'POST', data).then(val => { console.log(val) }).catch(val => { console.log(val) })
post without parameters, with request headers
const header = { 'Content-Type': 'text/html; charset=utf-8' } request('user/info', 'POST', null, header).then(val => { console.log(val) }).catch(val => { console.log(val) })
extended spelling
const userGet = async () => { const res = await request('user/info', 'GET') console.log(res) }
This article is reprinted from https://www.xxhzm.cn/archives/655
This site is for inclusion only, and the copyright belongs to the original author.