1. 原生 Ajax 的封装
封装思路:请求方式,请求地址,请求数据,回调函数
将请求的数据格式化成拼接的数据
/**
* jsonData 的格式:
* {
* url: 请求地址
* method: 请求类型
* data: 请求数据
* isAsync 是否异步
* success 成功的回调函数
* }
* */
function $ajax(jsonData) {
let formatData = "";
let xhr;
// 兼容低版本ie
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 格式化数据为 key1=value1&key2=value2 的格式
if(jsonData.data) {
let str = "";
let arr = [];
for(let key in jsonData.data) {
str = `${key}=${jsonData.data[key]}`
arr.push(str);
}
formatData = arr.join("&");
}
// get请求
if(jsonData.method.toLowerCase() == "get") {
xhr.open('get', jsonData.url + "?" + formatData, jsonData.isAsync);
xhr.send()
// post请求
} else if(jsonData.method.toLowerCase() == "post") {
xhr.open('post', jsonData.url, jsonData.isAsync);
xhr.setRequestHeader('Contenttype','application/x-www-form-urlencoded;charset=utf-8');
xhr.send(formatData);
}
// 状态值和状态码对应上后 执行成功的回调函数
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
jsonData.success(xhr.response);
}
}
}
调用实例:
$ajax({
url: "http://127.0.0.1:8082/process_get",
method: "get",
data: {
myname: myname,
myage: myage
},
isAsync: true,
success: function(res) {
console.log("successRes:", res);
}
})
}
2. Ts – Ajax 的封装
// 类型的约束
interface IOptions {
url: string;
type?: string; // ?代表可选类型 “GET” | "POST"
data: any;
timeout?: number;
}
function formatUrl(json) {
let dataArr = [];
json.t = Math.random();
for (let key in json) { //遍历数组
dataArr.push(`${key}=${encodeURIComponent(json[key])}`)
//encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
}
return dataArr.join('&');// 改写为需要的格式
}
export function ajax(options: IOptions) {
return new Promise((resolve, reject) => {
if (!options.url){
return
}; // 可能用 空对象 as any
options.type = options.type || 'GET';
options.data = options.data || {};
options.timeout = options.timeout || 10000;
let dataToUrlstr = formatUrl(options.data);
let timer;
const onStatechange = () =>{
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
clearTimeout(timer); // 超时取消
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
}
}
// 1.创建
let xhr;
if ((window as any).XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
// newObj = new ActiveXObject( servername.typename[, location])
// ActiveXObject 对象语法有这些部分:其中newObj是必选项。要赋值为 ActiveXObject 的变量名。
// 1. servername是必选项。提供该对象的应用程序的名称。
// 1. typename是必选项。要创建的对象的类型或类。
// 1. location是可选项。创建该对象的网络服务器的名称。
}
if (options.type.toUpperCase() === 'GET') {
// 2.连接
xhr.open('get', `${options.url}?${dataToUrlstr}`, true);
onStatechange()
// 3.发送
xhr.send();
} else if (options.type.toUpperCase() === 'POST') {
// 2.连接
xhr.open('post', options.url, true);
xhr.setRequestHeader('ContentType', 'application/x-www-form-urlencoded');
// 3.发送
onStatechange() //先注册后发送
xhr.send(options.data);
}
// 4.接收
//超时处理
if (options.timeout) {
timer = setTimeout(() => {
xhr.abort();
reject('超时');
}, options.timeout)
}
});
}