当前位置:首页 >> 网络编程

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

摘要:

  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 "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 = /&("',
        '"'    : '"',
        '¢'   : '¢',
        '¢'   : '¢',
        '£'  : '£',
        '£'   : '£',
        '¥'    : '¥',
        '¥'   : '¥',
        '€'   : '?',
        '€'  : '?',
        '§'   : '§',
        '§'   : '§',
        '©'   : '©',
        '©'   : '©',
        '®'    : '®',
        '®'   : '®',
        '™'  : '"codetitle">复制代码 代码如下:
$.ajax(ajaxSettings({
    url: '',
    data: ''
}))

以上所述就是本文的全部内容了,希望大家能够喜欢。