封装了jQuery的Ajax请求全局配置

前端技术 2023/09/02 JavaScript

摘要:

  jQuery已经成为项目中最常见的js库,也是前端开发最喜欢使用的库。下面是在项目中封装了jQuery的Ajax,分享给大家。

代码:

复制代码 代码如下:

// ajax 请求参数
var ajaxSettings = function(opt) {
    var url = opt.url;
    var href = location.href;
    // 判断是否跨域请求
    var requestType = \'jsonp\';
    if (url.indexOf(location.host) > -1)
        requestType = \'json\';
    requestType = opt.dataType || requestType;
    // 是否异步请求
    var async = (opt.async === undefined ? true : opt.async);
    return {
        url: url,
        async: async,
        type: opt.type || \'get\',
        dataType: requestType,
        cache: false,
        data: opt.data,
        success: function(data, textStatus, xhr) {
            /*
            *如果dataType是json,怎判断返回数据是否为json格式,如果不是进行转换
            * 成功数据通用格式
            *   {
            *       \"code\": 200,
            *       \"data\": [],
            *       \"success\": true // 成功
            *   }
            *   失败返回的数据
            *   {
            *       \"code\": 200,
            *       \"info\": \'error\',
            *       \"success\": false // 失败
            *   }
             */
            if((requestType === \'json\' || requestType === \"jsonp\") && typeof(data) === \"string\") {
                data = JSON.parse(data);
            }
            if(data.success) {
                opt.success(data);
            }

            if(opt.error) {
                opt.error(data);
            }

        },
        error: function(xhr, status, handler) {
            if (opt.error)
                opt.error();
        }
    };
};
function unescapeEntity(str) {
    var reg = /&(?:nbsp|#160|lt|#60|gt|62|amp|#38|quot|#34|cent|#162|pound|#163|yen|#165|euro|#8364|sect|#167|copy|#169|reg|#174|trade|#8482|times|#215|divide|#247);/g,
        entity = {
        \' \'   : \' \',
        \' \'   : \' \',
        \'<\'     : \'<\',
        \'<\'    : \'<\',
        \'>\'     : \'>\',
        \'&62;\'     : \'>\',
        \'&\'    : \'&\',
        \'&\'    : \'&\',
        \'\"\'   : \'\"\',
        \'\"\'    : \'\"\',
        \'¢\'   : \'¢\',
        \'¢\'   : \'¢\',
        \'£\'  : \'£\',
        \'£\'   : \'£\',
        \'¥\'    : \'¥\',
        \'¥\'   : \'¥\',
        \'€\'   : \'

本文地址:https://www.stayed.cn/item/5605

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。