基于Promise实现Ajax请求封装

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>

	<body>
		<script>
			// 基于Promise实现Ajax的封装
			function ajax(optins) {
				// 1. 解构获取传入的参数
				let { method, url, async, data, timeout } = optins

				// 2. 对象实例化
				const xhr = new XMLHttpRequest()

				// 3. 设置超时信息
				if (timeout && timeout > 0) {
					xhr.timeout = timeout
				}

				// 4. 返回一个Promise对象
				return new Promise((resolve, reject) => {
					// 5. 请求参数处理
					let params = []
					let encodeData = ''
					if (data instanceof Object) {
						Object.keys(data).forEach((key) => {
							params.push(
								`${encodeURIComponent(
									key
								)}=${encodeURIComponent(data[key])}`
							)
						})
						encodeData = params.join('&')
					}
					if (method === 'get') {
						const index = url.indexOf('?')
						if (index === -1) {
							url += '?'
						} else if (index !== url.length - 1) {
							url += '&'
						}
						url += encodeData
					}

					// 6. 初始化连接
					xhr.open(method, url, async)

					// 7.发送请求
					if (method === 'get') {
						xhr.send()
					} else {
						xhr.setRequestHeader(
							'Content-Type',
							'application/x-www-form-urlencoded'
						)
						xhr.send(encodeData)
					}

					// 8.接收请求
					xhr.onreadystatechange = () => {
						if (xhr.readyState === 4) {
							if (
								(xhr.status >= 200 && xhr.status < 300) ||
								xhr.status === 304
							) {
								resolve(xhr.response)
							} else {
								reject(xhr.response)
							}
						}
					}

					// 9.错误处理
					xhr.ontimeout = () => reject('请求超时')
					xhr.onerror = () => reject(err)
				})
			}

			let params = {
				method: 'get',
				url: 'https://api.uomg.com/api/rand.qinghua',
				async: true,
			}
			ajax(params).then((res) => {
				console.log(res, 'res')
				document.write(JSON.parse(res).content)
			})
		</script>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值