Files
ClassContent/历届学生/front-end-team-11/项目开发/学生项目/贡婉宝/得到/js/http/index.js
2024-09-27 02:06:13 +08:00

145 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class html {
//默认head
timeout=10000
Headermr={
'Content-Type': 'application/json;charset=utf-8'
}
constructor() {
//创建 XMLHttpRequest 对象
this.xhr = new XMLHttpRequest()
}
/*html.get({
url() -- 请求的地址
method: -- 请求的类型
data{ -- 数据 get 传输方式是在地址后拼接传输的 post 是在 send()里面传输的
id="1"
text="好的"
}
timeout: -- 网络请求超时间
header:{} -- 请求头
})*/
//promise
get(par) {
return new Promise((success,error)=>{
this.timeoutm(par)
let urldata = "" //创建一个变量储存数据 用来拼接
//遍历data
for (const key in par.data) {
urldata += `&${key}=${par.data[key]}` //进行拼接
}
console.log(urldata)
urldata = urldata.replace("&", ""); //将第一个开头的&替换成空
//创建一个新的HTTP请求,并指定该请求的方法、URL及验证信息
this.xhr.open("GET", `${config.getBaseUrl()}${par.url}?${urldata}`)
console.log("GET", `${config.getBaseUrl()}${par.url}?${urldata}`)
this.xhr.timeout=this.timeout;
this.RequestHeader(par.Header)
//将请求发送出去
this.xhr.send()
//回调函数对不同状态进行处理
this.statechange(success, error)
})
}
//callback
/*get传值方法
get(par) {
this.timeoutm(par)
let urldata = "" //创建一个变量储存数据 用来拼接
//遍历data
for (const key in par.data) {
urldata = `&${key}=${par.data[key]}` //进行拼接
}
urldata = urldata.replace("&", ""); //将第一个开头的&替换成空
//创建一个新的HTTP请求,并指定该请求的方法、URL及验证信息
this.xhr.open("GET", `${par.url}?${urldata}`)
this.xhr.timeout=this.timeout;
this.RequestHeader(par.Header)
//将请求发送出去
this.xhr.send()
//回调函数对不同状态进行处理
this.statechange(par.success, par.error)
}
//post传值方法
post(par) {
this.timeout(par)
//创建一个新的HTTP请求,并指定该请求的方法、URL及验证信息
this.xhr.open("POST", `${par.url}`)
this.RequestHeader(par.Header)
//将请求发送出去
this.xhr.send(JSON.stringify(par.data))
//回调函数对不同状态进行处理
this.statechange(par.success, par.error)
}*/
//回调函数
statechange(success, error) {
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
let data = JSON.parse(this.xhr.response)
switch (data.status) {
case 200:
success(data)
break;
case 404:
alert(data.msg)
console.error(this.xhr);
throw new Error(data.msg)
break;
default:
break;
}
} else {
error(this.xhr)
}
}
}
}
//多个请求头遍历
RequestHeader(Header={}){
Object.assign(Header,this.Headermr)
for (const key in Header) {
this.xhr.setRequestHeader(key,Header[key]);
}
}
timeoutm(par){
this.timeout=par.timeout||this.timeout;
}
}
var http = new html()
/*
let xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:3000/api/json/index")
xhr.setRequestHeader()
xhr.timeout()
xhr.send()
xhr.onreadystatechange = () => {
if (xhr.readyState == "4") {
if (xhr.status == "200") {
}
}
} */