封装简易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>

相关推荐
变与不变8063 天前
jQuery 核心语法与 jQuery AJAX
前端·ajax·jquery
牧瀬クリスだ7 天前
Ajax入门:从原生XHR到axios实战
java·spring boot·ajax·okhttp
liangshanbo121520 天前
面试题:页面需要发起大量 Ajax / HTTP 请求时,如何优化请求性能?
前端·http·ajax
RobinDevNotes20 天前
JAX 分布式训练,和 PyTorch 有什么不一样
人工智能·深度学习·ajax
小七在进步20 天前
类和对象(四)
java·javascript·ajax
wcy03101 个月前
POST为什么会发送两次请求
javascript·ajax
小刘在重生~1 个月前
Django|Ajax 入门、JSON 返回、ECharts 图表、文件上传完整笔记
ajax·django·json
零域码客1 个月前
一文掌握 jQuery + Flask 全栈核心知识点(前端交互 + 后端接口 + 前后端联调)
前端·python·ajax·flask·jquery·前后端联调·web全栈
2601_962097482 个月前
JavaScript 异步编程
javascript·ajax·回调函数·异步编程·子线程
lv__pf2 个月前
ajax的使用、json、jquery
ajax·json·jquery