网站是先制作后上线么,江苏省建筑人才网,网站建设连接数据库,网站设计好后如何发布目录 一#xff1a;步骤总结
二#xff1a;获取数据需求#xff1a;
三#xff1a;查找数据需求#xff1a;
四#xff1a;发送数据需求#xff1a;
一#xff1a;步骤总结
定义myAxios函数#xff0c;接收配置对象#xff0c;返回Promise对象发送XHR请求#…目录 一步骤总结
二获取数据需求
三查找数据需求
四发送数据需求
一步骤总结
定义myAxios函数接收配置对象返回Promise对象发送XHR请求设置默认请求方式为GET调用成功/失败处理程序使用myAxios函数获取数据
function myAxios(config){return new Promise((resolve,reject){//XHR请求//调用成功/失败的处理程序})
}
myAxios({
}).then(result{}).catch(error{})
其实底层部分源码框架是这样的只不过不同的需求往函数中传入的配置对象有些许不同
二获取数据需求
/** * 目标封装_简易axios函数_获取省份列表 * 1. 定义myAxios函数接收配置对象返回Promise对象 * 2. 发起XHR请求默认请求方法为GET * 3. 调用成功/失败的处理程序 * 4. 使用myAxios函数获取省份列表展示 */ //* 1. 定义myAxios函数接收配置对象返回Promise对象function myAxios(config) {return new Promise((resolve, reject) {//* 2. 发起XHR请求默认请求方法为GETconst xhr new XMLHttpRequest()xhr.open(config.method || GET, config.url)xhr.addEventListener(loadend, () {if (xhr.status 200 xhr.status 300) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})xhr.send()})}//* 3. 调用成功/失败的处理程序myAxios({url: https://hmajax.itheima.net/api/province1,}).then(//* 4. 使用myAxios函数获取省份列表展示result {console.log(result);document.body.innerHTML result.list.join(br)}).catch(error {document.body.innerHTML error.message})
三查找数据需求
/** * 目标封装_简易axios函数_获取地区列表 * 1. 判断有params选项携带查询参数核心 * 2. 使用URLSearchParams转换并携带到url上(核心) * 3. 使用myAxios函数获取地区列表 */ function myAxios(config) {return new Promise((resolve, reject) {const xhr new XMLHttpRequest()if (config.params) {//核心// 2.使用URLSearchParams将传参对象中的params查询对象进行转化并携带到url上const paramsObj new URLSearchParams(config.params)console.log(paramsObj);const queryString paramsObj.toString()//把查询字符串拼接在url?后面config.url ?${queryString}//核心}xhr.open(config.method || GET, config.url)xhr.addEventListener(loadend, () {if (xhr.status 200 xhr.status 300) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})xhr.send()})}myAxios({url: https://hmajax.itheima.net/api/area,params: {pname: 辽宁省,cname: 大连市}}).then(result {console.log(result);document.body.innerHTML result.list.join(br)})
四发送数据需求 /** * 目标封装_简易axios函数_注册用户 * 1. 判断有data选项携带请求体 * 2. 转换数据类型在send中发送 * 3. 使用myAxios函数完成注册用户 */
function myAxios(config) {return new Promise((resolve, reject) {const xhr new XMLHttpRequest()if (config.params) {const paramsObj new URLSearchParams(config.params)const queryString paramsObj.toString()config.url ?${queryString}}xhr.open(config.method || GET, config.url)xhr.addEventListener(loadend, () {if (xhr.status 200 xhr.status 300) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})//发送数据需求if (config.data) {xhr.setRequestHeader(Content-Type, application/json)//2.转换数据类型将data中的对象转换为json字符串在send中发送const jsonStr JSON.stringify(config.data)xhr.send(jsonStr)} else {xhr.send()}})}
//发送数据需求document.querySelector(.reg-btn).addEventListener(click, () {myAxios({url: https://hmajax.itheima.net/api/register,method: post,data: {username: itheima9999,password: 123456}}).then(result {console.log(result);}).catch(error {console.log(error);})})