提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:以下是本篇文章正文内容,下面案例可供参考
一、ajax的封装
需要判断url和param的值是否为空,如果为空则抛出错误让代码报错。且param必须为对象如果不为对象也抛出错误报错。如果返回的结果为字符串则需要用try和catch来捕获错误,之后用finally来解决。
二、使用步骤
1.get
代码如下:
const axios = {
get(url, param = {}) {
//url 和param 不能为空 且和param必须是对象
if (!url || !param) throw new Error('url或param不能为空');
// if(param)
// console.log(param.toString());
// console.log(param.__proto__.constructor);
if (param.toString() != '[object Object]') throw new Error('param必须是对象');
let xhr = new XMLHttpRequest();
// url?k1=v1&k2=v2...
// 遍历传递的参数,进行拼接
let str = '';
// console.log(param);
for (let attr in param) {
str = str + '&' + attr + '=' + param[attr]
}
// console.log(str); // &username=zs&age=22
// 截取 下标为&以后的有效字符串
str = str.substr(1);
// console.log(str);
// 如果str为空则不拼接
// str 为空是false则不拼接,str有值为true,则执行后面表达式
str && (url = url + '?' + str)
return new Promise((resolve, reject) => {
// console.log(url);
xhr.open('get', url);
xhr.send();
xhr.onload = function () {
// 成功
// console.log(xhr.response);
// resolve(xhr.response)
// 有的返回结果是 json字符串,有的是普通字符串,我们需要把json转化
let res = '';
try { // 可能出错的代码
res = JSON.parse(xhr.response)
} catch{ // 出了错误之后怎么办,json解析失败
res = xhr.response
} finally { // 不管成功还是失败都走这里
resolve(res)
}
}
xhr.onerror = function (abc) {
// 失败
reject(abc)
}
})
}
2.post
代码如下(示例):
const axios = {
post(url, param = {}) {
//url 和param 不能为空 且和param必须是对象
if (!url || !param) throw new Error('url或param不能为空');
// if(param)
// console.log(param.toString());
// console.log(param.__proto__.constructor);
if (param.toString() != '[object Object]') throw new Error('param必须是对象');
let xhr = new XMLHttpRequest();
// url?k1=v1&k2=v2...
// 遍历传递的参数,进行拼接
let str = '';
// console.log(param);
for (let attr in param) {
str = str + '&' + attr + '=' + param[attr]
}
// console.log(str); // &username=zs&age=22
// 截取 下标为&以后的有效字符串
str = str.substr(1);
// console.log(str);
return new Promise((resolve, reject) => {
// console.log(url);
xhr.open('post', url);
//设置请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(str);
xhr.onload = function () {
// 成功
// console.log(xhr.response);
// resolve(xhr.response)
// 有的返回结果是 json字符串,有的是普通字符串,我们需要把json转化
let res = '';
try { // 可能出错的代码
res = JSON.parse(xhr.response)
} catch{ // 出了错误之后怎么办,json解析失败
res = xhr.response
} finally { // 不管成功还是失败都走这里
resolve(res)
}
}
xhr.onerror = function (abc) {
// 失败
reject(abc)
}
})
},
// 将get和post中重复的代码,封装到下面方法
// 找出get和post互相之间重复的部分和不重复的部分
http() {
}
}
}
总结
post和get的代码有很多重复,可以用一个新的封装同时实现post和get。我会在下篇博客介绍这个封装。
冰冻三尺,非一日之寒。
外韧之味,久则可厌;读书之味,愈久愈深。