[Axios] 基于Promise封装属于自己的Ajax库

基于Promise封装属于自己的Ajax库

  • 自己封装ajax库

    ;(function anonymous(window) {
        //支持设置默认的参数配置项
        let _default = {
            method: 'GET',
            url: '',
            baseURL: '',
            headers: {},
            dataType: 'JSON',
            //POST系列请求基于请求主体传递给服务器的内容
            data: null,
            //GET系列请求基于问号传参传递给服务器的内容
            params: null,
            //设置缓存
            cache: true
        };
    
        //基于PROMISE设计模式管理AJAX请求
        let ajaxPromise = function ajaxPromise(options) {
            //OPTIONS中融合了:默认配置信息、用户基于DEFAULTS修改的信息、用户执行GET/POST方法时候传递的配置信息,越靠后的优先级越高
            let {url, baseURL, method, data, dataType, headers, cache, params} = options;
    
            //把传递的参数进一步进行处理
            if (/^(GET|DELETE|HEAD|OPTIONS)$/i.test(method)) {
                //GET系列
                if (params) {
                    url += `${ajaxPromise.check(url)}${ajaxPromise.formatData(params)}`;
                }
                if (cache === false) {
                    url += `${ajaxPromise.check(url)}_=${+(new Date())}`;
                }
                data = null;//GET系列请求主体就是什么都不放
            } else {
                //POST系列
                if (data) {
                    data = ajaxPromise.formatData(data);
                }
            }
    
            //基于PROMISE发送AJAX
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest;
                xhr.open(method, `${baseURL}${url}`);
                //如果HEADERS存在,我们需要设置请求头
                if (headers !== null && typeof headers === 'object') {
                    for (let attr in headers) {
                        if (headers.hasOwnProperty(attr)) {
                            let val = headers[attr];
                            if (/[\u4e00-\u9fa5]/.test(val)) {
                                //VAL中包含中文:我们把它进行编码
                                //encodeURIComponent/decodeURIComponent
                                val = encodeURIComponent(val);
                            }
                            xhr.setRequestHeader(attr, val);
                        }
                    }
                }
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (/^(2|3)\d{2}$/.test(xhr.status)) {
                            let result = xhr.responseText;
                            dataType = dataType.toUpperCase();
                            dataType === 'JSON' ? result = JSON.parse(result) : (dataType === 'XML' ? result = xhr.responseXML : null);
                            resolve(result);
                            return;
                        }
                        reject(xhr.statusText);
                    }
                };
                xhr.send(data);
            });
        };
    
        //把默认配置暴露出去,后期用户在使用的时候可以自己设置一些基础的默认值(发送AJAX请求的时候按照用户配置的信息进行处理)
        ajaxPromise.defaults = _default;
    
        //把对象转换为URLENCODED格式的字符串
        ajaxPromise.formatData = function formatData(obj) {
            let str = ``;
            for (let attr in obj) {
                if (obj.hasOwnProperty(attr)) {
                    str += `${attr}=${obj[attr]}&`;
                }
            }
            return str.substring(0, str.length - 1);
        };
        ajaxPromise.check = function check(url) {
            return url.indexOf('?') > -1 ? '&' : '?';
        };
    
        //GET
        ['get', 'delete', 'head', 'options'].forEach(item => {
            ajaxPromise[item] = function anonymous(url, options = {}) {
                options = {
                    ..._default,//默认值或者基于defaults修改的值
                    ...options,//用户调取方法传递的配置项
                    url: url,//请求的URL地址(第一个参数:默认配置项和传递的配置项中都不会出现URL,只能这样获取)
                    method: item.toUpperCase()//以后执行肯定是ajaxPromise.head执行,不会设置METHODS这个配置项,我们自己需要配置才可以
                };
                return ajaxPromise(options);
            };
        });
    
        //=>POST
        ['post', 'put', 'patch'].forEach(item => {
            ajaxPromise[item] = function anonymous(url, data = {}, options = {}) {
                options = {
                    ..._default,
                    ...options,
                    url: url,
                    method: item.toUpperCase(),
                    data: data
                };
                return ajaxPromise(options);
            };
        });
    
        window.ajaxPromise = ajaxPromise;
    })(window);
    

  • 测试

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
    </head>
    <body>
    <script src="js/ajaxPromise.js"></script>
    <script>
        //DEFAULT
        ajaxPromise.defaults.baseURL = 'https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp';
    
        //SEND
    
        //GET1
        ajaxPromise.get('/list').then((result) => {
            console.log(result);
        });
        //GET2
        ajaxPromise.get('/info', {
            params: {
                id: 1000
            },
            cache: false
        }).then((result) => {
            console.log(result);
        });
        //POST
        ajaxPromise.post('/add', {
            name: 'xxx',
            age: 9
        }, {
            headers: {
                'content-type': 'x-www-form-urlencoded'
            }
        }).then((result) => {
            console.log(result);
        });
    </script>
    </body>
    </html>
    
AI实战-仿真交易欺诈行为分类数据集分析预测实例(含10个源代码+419.69 KB完整的数据集) 代码手工整理,无语法错误,可运行。 包括:10个代码,共49.42 KB;数据大小:1个文件共419.69 KB。 使用到的模块: pandas os sklearn.model_selection.train_test_split sklearn.ensemble.RandomForestClassifier sklearn.metrics.classification_report imblearn.over_sampling.SMOTE sklearn.linear_model.LogisticRegression sklearn.metrics.accuracy_score datetime.datetime sklearn.svm.SVC seaborn sklearn.preprocessing.StandardScaler sklearn.preprocessing.OrdinalEncoder sklearn.compose.ColumnTransformer imblearn.pipeline.Pipeline numpy matplotlib.pyplot statsmodels.formula.api sklearn.model_selection.StratifiedKFold sklearn.metrics.roc_auc_score contextlib pickle sklearn.pipeline.Pipeline sklearn.preprocessing.OneHotEncoder sklearn.preprocessing.PowerTransformer torch torch.nn torch.nn.BCELoss torch.optim.Adam warnings scipy.stats.normaltest scipy.stats.chi2_contingency wolta.data_tools.col_types wolta.data_tools.seek_null wolta.data_tools.unique_amounts wolta.feature_tools.list_deletings wolta.data_tools.make_numerics wolta.data_tools.stat_sum wolta.data_tools.corr_analyse collections.Counter wolta.model_tools.compare_models wolta.model_tools.get_best_model sklearn.metrics.confusion_matrix sklearn.metrics.ConfusionMatrixDisplay sklearn.ensemble.GradientBoostingClassifier xgboost sklearn.model_selection.GridSearchCV sklearn.preprocessing.LabelEncoder sklearn.ensemble.StackingClassifier sklearn.metrics.roc_curve plotly.express wordcloud.WordCloud wordcloud.STOPWORDS
AI实战-阿尔茨海默氏病患者的健康信息数据集分析预测实例(含17个源代码+591.06 KB完整的数据集) 代码手工整理,无语法错误,可运行。 包括:17个代码,共143.32 KB;数据大小:1个文件共591.06 KB。 使用到的模块: numpy pandas os seaborn matplotlib.pyplot sklearn.model_selection.train_test_split sklearn.ensemble.RandomForestClassifier sklearn.metrics.accuracy_score sklearn.metrics.confusion_matrix sklearn.metrics.classification_report sklearn.preprocessing.LabelEncoder sklearn.preprocessing.StandardScaler warnings sklearn.svm.SVC mealpy.GA mealpy.Problem sklearn.neural_network.MLPClassifier mealpy.BinaryVar sklearn.exceptions.ConvergenceWarning IPython.display.clear_output sklearn.utils.resample sklearn.compose.ColumnTransformer sklearn.pipeline.Pipeline sklearn.preprocessing.PowerTransformer sklearn.decomposition.PCA sklearn.linear_model.LogisticRegression sklearn.metrics.precision_score sklearn.metrics.recall_score sklearn.metrics.f1_score sklearn.preprocessing.MinMaxScaler sklearn.metrics.ConfusionMatrixDisplay sklearn.model_selection.RepeatedKFold sklearn.model_selection.cross_val_score sklearn.model_selection.RandomizedSearchCV xgboost.XGBClassifier tensorflow pickle plotly.express plotly.subplots.make_subplots plotly.graph_objects sklearn.model_selection.GridSearchCV sklearn.model_selection.cross_validate sklearn.tree.DecisionTreeClassifier yellowbrick.classifier.ClassPredictionError yellowbrick.classifier.ROCAUC yellowbrick.classifier.ConfusionMatrix sklearn.ensemble.GradientBoostingClassifier lightgbm.LGBMClassifier catboost.CatBoostClassifier imblearn.under_sampling.RandomUnderSampler imblearn.over_sampling.RandomOverSampler sklearn.metrics.matthews_corrcoef optuna torch torch.nn torch.optim imblearn.pipeline.Pipeline imblearn.over_sampling.SMOTE sklearn.ensemble.AdaBoostClassifier sklearn.neighbors.KNeighborsClassifier sklearn.discriminant_analysis.LinearDiscriminantAnalysis sklearn.pipeline.make_pipeline collections.Counter sklearn.preprocessing.OneHotEncoder sklearn.model_selection.cross_val_predict sklearn.metrics.precision_recall_curve sklearn
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值