赞
踩
直接上代码
- /**
- * ajax函数
- * @param {Object} options 请求传入的对象参数
- */
- function ajax(options = {}) {
- // 1. 参数校验
- // 校验请求地址必传,而只能是字符串类型
- if (!options.url || typeof (options.url) != 'string') throw Error('url必传,只能是字符串');
- // 校验请求方式 只能是post或get 或者不传递
- if (!(typeof options.method === 'undefined' || /^(get|post)$/i.test(options.method))) throw Error('method只能是post或get');
- // 校验请求方式 只能是post或get 或者不传递
- if (!(typeof options.dataType === 'undefined' || /^(string|json)$/i.test(options.dataType))) throw Error('dataType只能是json或string');
- // 校验携带的参数 只能是对象 或者不传递
- if (!(typeof options.data === 'undefined' || Object.prototype.toString.call(options.data) === '[object Object]')) throw Error('data只能是对象');
- // 校验请求是否异步 只能是布尔类型 或者不传递
- if (!(typeof options.async === 'undefined' || typeof options.async === 'boolean')) throw Error('async只能是布尔值');
- // 校验请求头 只能是对象 或者不传递
- if (!(typeof options.header === 'undefined' || Object.prototype.toString.call(options.header) === '[object Object]')) throw Error('header只能是对象');
- // 校验成功函数 只能是函数 或者不传递
- if (!(typeof options.success === 'undefined' || typeof options.success === 'function')) throw Error('success只能是函数');
- // 校验错误函数 只能是函数 或者不传递
- if (!(typeof options.error === 'undefined' || typeof options.error === 'function')) throw Error('error只能是函数');
-
- // console.log( options )
- // 2. 准备ajax请求的默认值
- let defInfo = {
- url: options.url,
- method: options.method ? options.method : 'get',
- data: options.data ? options.data : {},
- dataType: options.dataType ? options.dataType : 'string',
- async: typeof options.async==='boolean'?options.async:true,
- //?? 空值合并运算符 当左侧的操作数为null 或者undefined 时,返回其右侧操作数,否则返回左侧操作数。
- //async: options.async ?? true,
- header: { 'content-type': 'application/x-www-form-urlencoded', ...options.header },
- success: options.success ? options.success : () => { },
- error: options.error ? options.error : () => { },
- }
- // console.log( defInfo )
- // 3. 组装查询字符串
- let queryStr = '';
- // 遍历defInfo.data
- for (const key in defInfo.data) {
- queryStr += `${key}=${defInfo.data[key]}&`;
- }
- queryStr = queryStr.slice(0, -1);
- // 判断是否将查询字符串拼接到 地址中
- if (/get/i.test(defInfo.method)) defInfo.url += `?${queryStr}`;
-
- // 创建ajax对象
- let xhr = new XMLHttpRequest();
- // 配置请求信息
- xhr.open(defInfo.method, defInfo.url, defInfo.async);
- // 设置请求头
- for (const key in defInfo.header) {
- xhr.setRequestHeader(key, defInfo.header[key])
- }
-
- // 发送请求
- /post/i.test(defInfo.method) ? xhr.send(queryStr) : xhr.send();
- // 接受响应
- xhr.onload = function () {
- let res = xhr.responseText;
- try {
- // 判断是否需要json转换
- if (defInfo.dataType === 'json') {
- res = JSON.parse(res);
- }
- // 执行成功回调---将接受的响应数据作为实参传递
- defInfo.success(res)
- } catch (err) {
- // 执行失败回调---将接受的异常信息作为实参传递
- defInfo.error(err)
- }
- }
- }
- <script src="./ajax.js"></script>
- <script>
- // throw Error('异常了')
- ajax({
- url:'http://localhost:8888/users/login',
- // url:'http://localhost:8888/test/first',
- method:'post',
- data:{username:'admin',password:123456},
- // async:false,
- dataType:'json',
- // header:{'authorization':'123456','content-type':'application/json'},
- success:(res)=>{
- console.log( res )
- },
- error:(r)=>{
- console.log( r )
- }
- })
-
- </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。