封装简易axios函数 注册用户 提交表单POST

<!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>封装简易axios函数 注册用户 提交表单POST</title>

</head>

<body>

<button class="reg-btn">注册用户</button>

<script>

/**

* 目标:封装_简易axios函数_注册用户

* 1. 判断有data选项,携带请求体

* 2. 转换数据类型,在send中发送

* 3. 使用myAxios函数,完成注册用户

*/

function myAxios(config) {

return new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest()

if (config.params) {

const paramsObj = new URLSearchParams(config.params)

const queryString = paramsObj.toString()

config.url += `?${queryString}`

}

xhr.open(config.method || 'GET', config.url)

xhr.addEventListener('loadend', () => {

if (xhr.status >= 200 && xhr.status < 300) {

resolve(JSON.parse(xhr.response))

} else {

reject(new Error(xhr.response))

}

})

// 1. 判断有data选项,携带请求体

if (config.data) {

// 2. 转换数据类型,在send中发送

const jsonStr = JSON.stringify(config.data)

xhr.setRequestHeader('Content-Type', 'application/json')

xhr.send(jsonStr)

} else {

// 如果没有请求体数据,正常的发起请求

xhr.send()

}

})

}

document.querySelector('.reg-btn').addEventListener('click', () => {

// 3. 使用myAxios函数,完成注册用户

myAxios({

url: 'http://hmajax.itheima.net/api/register',

method: 'POST',

data: {

username: 'itheima999',

password: '666666'

}

}).then(result => {

console.log(result)

}).catch(error => {

console.dir(error)

})

})

</script>

</body>

</html>

相关推荐
鬼手点金4 天前
Scrapy 网络爬虫框架
爬虫·python·scrapy·ajax·html·json·requsts
云水一下5 天前
零基础玩转bWAPP靶场(四十六):XSS - Reflected (AJAX/JSON)
web安全·ajax·json·xss·bwapp·reflected
starzy19905 天前
Spark 核心之自定义累加器以及版本对比变化深度剖析
大数据·ajax·spark
云水一下6 天前
零基础玩转bWAPP靶场(四十七):XSS - Reflected (AJAX/XML)
xml·web安全·ajax·xss·bwapp
BD_Marathon8 天前
开发Spark应用程序
大数据·ajax·spark
HackTwoHub8 天前
Fastjson1全版本(1.2.47→1.2.83 )漏洞利用3万字完整总结、绕过分析、探测、WAF 绕过与 Gadget 汇总
前端·javascript·人工智能·安全·ajax·网络安全·自动化
starzy199017 天前
Spark 核心之 Driver 原理剖析
大数据·ajax·spark
BD_Marathon23 天前
Spark数据源
大数据·ajax·spark
zzx2006__1 个月前
Ajax➕node.js➕webpack
ajax·webpack·node.js
南川琼语1 个月前
HTTP——AJAX
前端·javascript·ajax