有时候我们需要统一整个项目的ajax请求格式,比如在所有的ajax请求中附加上一些必须的参数,这时就不可能一个一个的去加了,我们可以在jquery的ajax方法的基础上再封装一层做统一处理,具体代码如下,供参考:
/** * ajax post 提交 * @param param 参数(json格式) * @param successCallback 成功后的回调函数 * @return * @author www.phpernote.com */ function sendAjax(param, successCallback) { if (param) { var gid = getCookie('gid'), passport = getCookie('passport'), auth_code = getCookie('auth_code'), access_token = getCookie('access_token'), info = {gid: gid, passport: passport, auth_code: auth_code, access_token: access_token, client: 'h5', ver: ''}; param = Object.assign(info, param);//参数合并 } $.ajax({ type: 'post', url: api_url, data: param, dataType: 'json', timeout: ajax_timeout, cache: false, async: true, success: function (data) { if (data.errcode == '2001' && location.href.indexOf('login') == -1) { location.href = './login.html'; return; } successCallback(data); }, error: function () { if (!isDev) { alert('请求发生错误'); } } }); }
调用如:
sendAjax({action: 'getDayStatistics', tdate: '2020-04-28'}, function (data) { var app = new Vue({ el: '#dayStatisticsContent', data: { totalShouru: data.total_shouru, totalZhichu: data.total_zhichu, shouruList: data.shouru_list, zhichuList: data.zhichu_list } }); });