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

相关推荐
之歆3 天前
Ajax 基础技术深度解析:XHR 从入门到跨域
前端·ajax·okhttp
之歆3 天前
Ajax 进阶:跨域、CORS、JSONP 与请求封装实战
前端·javascript·ajax
sugar__salt3 天前
前端Ajax核心原理与实战:从异步机制到接口请求全解析
前端·javascript·ajax
YHHLAI4 天前
Ajax — 异步数据交互
ajax·okhttp·交互
meilindehuzi_a4 天前
深入理解 Ajax 异步请求:从 XMLHttpRequest 到 Node.js HTTP 服务实践
http·ajax·node.js
拾年2754 天前
从零手写 Ajax:用原生 XHR 搭建前后端交互全流程
前端·javascript·ajax
零壹AI实验室16 天前
NVIDIA RTX Spark深度测评:个人AI智能体时代真的来了?
人工智能·ajax·spark
清水白石00817 天前
Python 变量的本质:从“盒子思维”到“引用思维”,彻底理解赋值到底发生了什么
java·python·ajax
来恩100321 天前
jQuery对Ajax的支持
前端·ajax·jquery