简单的ajax封装

// ajax发送post请求返回 json 数据
function requestJSON(params) {
    params.dataType = 'json';
    sendPost(params);
}

// ajax发送post请求返回 string字符串
function requestString(params) {
    params.dataType = 'text';
    sendPost(params);
}

// ajax发送post请求
function sendPost(params) {
    params.type = 'post';
    sendRequest(params);
}

// ajax发送get请求
function request(params) {
    params.type = 'get';
    sendRequest(params);
}

// ajax请求封装
function sendRequest(params) {
    params = $.extend({}, { async: true }, params);
    $.ajax({
        url: params.url,
        data: params.data,
        type: params.type,
        dataType: params.dataType,
        success: params.success,
        async: params.async,
        beforeSend: function () {
            if (typeof (params.before) == 'function') {
                params.before();
            }
            else {
                // 页面数据请求提示loading效果
                jQuery('body').Loading({ marginTop: '-300px;' });
            }
        },
        error: function () {
            jQuery('body').hideLoading();
            if (typeof (params.error) == 'function') params.error();
        },
        complete: function () {

            if (typeof (params.complete) == 'function') {
                params.complete();
            }
            else {
                // 请求完成处理
                jQuery('body').hideLoading();
            }
        }
    });
}

原文地址:https://www.cnblogs.com/huangf714/p/5795051.html