1 Star 0 Fork 0

身怀绝技的傀儡师/a1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ajax的封装.html 2.68 KB
一键复制 编辑 原始数据 按行查看 历史
身怀绝技的傀儡师 提交于 2022-12-07 19:51 . 99
<!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>Document</title>
</head>
<body>
<button>ajax请求数据</button>
<script>
function sendAjax(obj) {
// console.log(obj.url)
// console.log(obj.method)
if (obj.method === undefined) {
obj.method = 'get'
} else {
if (obj.method.toLowerCase() != 'get' && obj.method.toLowerCase() != 'post' && obj.method.toLowerCase() != 'put' && obj.method.toLowerCase() != 'delete') {
throw new Error('请求方式不正确')
}
}
if (obj.url === undefined) {
throw new Error('请求地址不能为空')
} else {
if (typeof obj.url != 'string') {
throw new Error('请求地址不正确!')
}
}
if (obj.async === undefined) {
obj.async = true
} else {
if (typeof obj.async != 'boolean') {
throw new Error('async必须的布尔值')
}
}
var xhr = new XMLHttpRequest()
xhr.open(obj.method, obj.url, obj.async)
if (obj.data != undefined) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
if (typeof obj.data === 'object') {
var arr = []
for (var key in obj.data) {
arr.push(key + '=' + obj.data[key])
}
xhr.send(arr.join('&'))
} else {
xhr.send(obj.data)
}
} else {
xhr.send()
}
if (obj.async === false) {
var msg = xhr.responeText
obj.success(msg)
} else {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var msg = xhr.responeText
obj.success(msg)
}
}
}
}
}
document.querySelector('button').onclick =function()
{
{
var obj = {
method: 'get',
url: 'http://localhost:3000/users',
async: '',
success:''
};
sendAjax(obj)
}
}
</script>
</body>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/a-puppet-with-unique-skills/a1.git
git@gitee.com:a-puppet-with-unique-skills/a1.git
a-puppet-with-unique-skills
a1
a1
master

搜索帮助