js基础知识——ajax的封装
一、ajax的封装思路
- 参数:
- 请求方式:选填,默认为get,形参名:type
- 请求地址:必填 形参名:url
- 请求为同步或异步:选填,默认值为true ,形参名:async
- 请求需要携带的参数:选填 默认为空字符串'',形参名:data
- 返回值:需要返回一个promise对象,后续可以通过 .then 或 async/await 去使用
二、ajax的封装
function myAjax(options){
if (options.url === undefined) throw new Error('参数中缺少必传项 url')
if (!((options.type === undefined || typeof(options.type) === 'string') )) {
throw new Error('参数中的type值的类型目前仅值从 string')
}
const _options = {
url: options.url,
type: options.type || 'get',
data:options.data || '',
async: options.async ?? true
}
console.log('如果执行到这个位置,就可以发送请求了',_options)
const xhr = new XMLHttpRequest()
xhr.open(_options.type,_options.url,_options.async)
xhr.onload = function () {
console.log(xhr.responseText)
}
xhr.send()
}
myAjax({
url:'http://localhost:8888/test/first'
})