Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/张婷/练习/ajax/ajax封装练习/ajax回调函数.js
2024-09-27 02:06:13 +08:00

75 lines
2.9 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 Ajax {
constructor() {
this.ajax = new XMLHttpRequest();
// 请求监听全局只运行一次,是异步的,有需要(先send再监听)就运行,不需要就待机
// 监听放这里参数很难回调出去,原因是get和readystate是相互独立(局部)的
// this.readystatechange();
// 局部变全局
this.success = null
}
// java中“@”大多代表注解的意思。那么@param是用来在DAO层中声明参数的注解方式。
// @ param标签可以归档方法或构造器的某个单一参数,或者归档类、接口以及泛型方法的类型参数。
// 在使用@ param标签时,我们应该针对方法的每一个参数都使用一个该标签。
// 每个段落的第一个词会被当作参数名,而余下的部分则会被当作是对它的描述。
/**
* 接收多个参数,所以封装一个对象直接接收对象
*
* @param{*}params
* {
* 请求的网址 url:"",
*
* 请求的参数 data:{
* (对象) id:1,
* page:2
* },
*
* 请求头 header:{
* (对象) 'Content-Type':'application/json;charset=UTF-8'
* },
*
* 请求成功的回调 success:(res)=>{},
* (方法)
*
* 请求失败的回调 error:(err)=>{不同地方的错误提示也不一样,可以不用但必须要有},
* }
*/
get(params) {
this.success = params.success
var str = ""
// get的传参形式是url+?key=value,但我们的参数是对象,所以要转换(字符串拼接和符号替换)
// 对对象遍历,拿到值
// this.ajax.open("GET","http://localhost")
for (const key in params.data) {
// console.log("key",key);
str += `&${key}=${params.data[key]}`
}
str = str.replace("&", "?")
this.ajax.open("GET", `${params.url}${str}`)
// console.log(`${params.url}${str}`);
this.ajax.send();//send必须要有状态监听,多个共用一个状态监听即可
// 监听放在这里用可以直接把后端的参数回调出去
this.readystatechange(params.success, params.error)
}
post() { }
readystatechange(success,error) {
this.ajax.onreadystatechange = () => {
// console.log(this.ajax.readyState);
if (this.ajax.readyState == 4) {
// 后端给我们的数据保存在response和responseText里
if (this.ajax.status == 200) {
var data = JSON.parse(this.ajax.responseText)
// console.log(date);
success(data)
this.success(data)
} else {
error(this.ajax)
}
}
}
}
}
var ajax = new Ajax();