封装简易axios函数 获取数据 GET

<!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函数 获取数据 GET</title>

</head>

<!--

步骤:

1.定义myAxios函数,接收配置对象,返回Promise对象

2.发起XHR请求,默认请求方法为GET

3.调用成功/失败的处理程序

4.调用myAxios函数

-->

<body>

<p class="my-p"></p>

<script>

function myAxios(config) {

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

const xhr = new XMLHttpRequest()

// 1. 判断有params选项,携带查询参数

if (config.params) {

// 2. 使用URLSearchParams转换,并携带到url上

const paramsObj = new URLSearchParams(config.params)

const queryString = paramsObj.toString()

// 把查询参数字符串,拼接在url?后面

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

}

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

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

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

// xhr.status查看响应状态码

resolve(JSON.parse(xhr.response))

} else {

reject(new Error(xhr.response))

}

})

xhr.send()

})

}

// 3. 使用myAxios函数,获取地区列表

myAxios({

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

params: {

pname: '辽宁省',

cname: '大连市'

}

}).then(result => {

console.log(result)

document.querySelector('.my-p').innerHTML = result.list.join('<br>')

})

</script>

</body>

</html>

相关推荐
2503_9284115618 小时前
9.8 ajax+php基础语法
ajax·okhttp·php
Yvonne爱编码2 天前
简述ajax、node.js、webpack、git
前端·git·ajax·webpack·node.js·visual studio
长城20245 天前
jQuery的$.Ajax方法分析
ajax·jquery·异步提交
芜青6 天前
JavaScript手录进阶01-跨域问题
开发语言·javascript·ajax·ecmascript
长城20246 天前
JavaScript中的XMLHttpRequest对象分析
开发语言·javascript·ajax·xmlhttprequest·xhr·ajax技术
JosieBook6 天前
【SpringBoot】20 - SpringBoot中的Ajax和MyBatis究竟是什么?
spring boot·ajax·mybatis
苏纪云7 天前
Ajax笔记(下)
前端·javascript·笔记·ajax
IT 前端 张7 天前
Axios与Ajax:现代Web请求大比拼
前端·javascript·ajax
知识分享小能手13 天前
React学习教程,从入门到精通, React教程:构建你的第一个 React 应用(1)
前端·javascript·vue.js·学习·react.js·ajax·前端框架
wuzuyu36513 天前
SyntaxError: Failed to execute ‘open‘ on ‘XMLHttpRequest‘: Invalid URL
ajax·html·api