Jquery ajax封装

function postData(url, data, fnObj) {
    $.ajax( {
            url: url,
            type: "post",
            headers: {
                Authorization: "Bearer " + token
            },
            data: data,
            success: function () {
                if (fnObj && typeof fnObj.fn === 'function') {
                    fnObj.fn.apply(this, arguments);
                }
            },
            error: function (msg, st, e) {
                if (fnObj && typeof fnObj.err === 'function') {
                    fnObj.err.apply(this, arguments);
                }
            }
        });
}
function getData(url, fnObj) {
    $.ajax( {
            url: url,
            type: "get",
            headers: {
                Authorization: "Bearer " + token
            },
            success: function () {
                if (fnObj && typeof fnObj.fn === 'function') {
                    fnObj.fn.apply(this, arguments);
                }
            },
            error: function (msg, st, e) {
                if (fnObj && typeof fnObj.err === 'function') {
                    fnObj.err.apply(this, arguments);
                }
            }
        });
}

function postTxtData(url, data, fnObj){
    $.ajax( {
        url:url,
        type: "post",
        contentType: 'text/plain',
        dataType: 'json',
        headers: {
            Authorization: "Bearer " + token
        },
        data:JSON.stringify(data),
        success: function () {
            if (fnObj && typeof fnObj.fn === 'function') {
                fnObj.fn.apply(this, arguments);
            }
        },
        error: function (msg, st, e) {
            if (fnObj && typeof fnObj.err === 'function') {
                fnObj.err.apply(this, arguments);
            }
        }
    });
}

/*调用*/
 postTxtData(url, { type: 1 }, {
    fn: function (res) {
       ...
    },
    err: function (error) {
      ...
    }
 });

你可能感兴趣的:(Jquery ajax封装)