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

相关推荐
Run Freely9372 天前
Ajax-day2(图书管理)-弹框显示和隐藏
前端·javascript·ajax
xkroy2 天前
ajax
前端·javascript·ajax
元亓亓亓2 天前
JavaWeb--day3--Ajax&Element&路由&打包部署
android·ajax·okhttp
Yvonne爱编码2 天前
AJAX入门-URL、参数查询、案例查询
前端·javascript·ajax
lwprain3 天前
龙蜥8.10中spark各种集群及单机模式的搭建spark3.5.6(基于hadoop3.3.6集群)
大数据·ajax·spark
知识分享小能手3 天前
React学习教程,从入门到精通,React AJAX 语法知识点与案例详解(18)
前端·javascript·vue.js·学习·react.js·ajax·vue3
Yvonne爱编码4 天前
构建高效协作的桥梁:前后端衔接实践与接口文档规范详解
前端·git·ajax·webpack·node.js
William_cl4 天前
MVC 中 AJAX 与前后端交互深度实战(含独家避坑与场景化方案)
ajax·mvc·交互
Yvonne爱编码5 天前
AJAX入门-AJAX 概念和 axios 使用
前端·javascript·ajax·html·js
闯闯桑5 天前
Spark 中spark.implicits._ 中的 toDF和DataFrame 类本身的 toDF 方法
大数据·ajax·spark·scala