/** * Created by Mai on 2017/4/20. */ /** * 设置全局的AJAX请求默认选项 * 主要设置了AJAX请求遇到Session过期的情况 */ $.ajaxSetup({ complete: function (data) { if (data.responseJSON&&data.responseJSON.ret_code && data.responseJSON.ret_code == 99) { alert(data.responseJSON.ret_msg); var top = getTopWindow(); setTimeout('top.location.href = "/login";', 300); } } }); /** * 在页面中任何嵌套层次的窗口中获取顶层窗口 * @return 当前页面的顶层窗口对象 */ function getTopWindow() { var p = window; while (p != p.parent) { p = p.parent; } return p; } var CommonAjax = { get:function (url,data,cb,dataType) { $.get(url,data,cb,dataType) }, post: function (url, data, successCallback, errorCallback) { $.ajax({ type:"POST", url: url, data: {'data': JSON.stringify(data)}, dataType: 'json', cache: false, timeout: 150000, success: function(result){ if (result.error === 0) { if (successCallback) { successCallback(result.data); } } else { alert('error: ' + result.message); if (errorCallback) { errorCallback(result.message); } } }, error: function(jqXHR, textStatus, errorThrown){ alert('url: ' + url +' error ' + textStatus + " " + errorThrown); if (errorCallback) { errorCallback(); } } }); }, postRationLib: function (url, data, successCallback, errorCallback) { $.ajax({ type:"POST", url: url, data: data, dataType: 'json', cache: false, timeout: 50000, success: function(result){ if (!result.error) { if (successCallback) { successCallback(result.data); } } else { alert('error: ' + result.message); if (errorCallback) { errorCallback(); } } }, error: function(jqXHR, textStatus, errorThrown){ alert('error ' + textStatus + " " + errorThrown); if (errorCallback) { errorCallback(); } } }); }, postEx: function(url, params, dftTimeOutMilSec, isAsync, successCallback, failCallback, exceptionCallback){ $.ajax({ type:"POST", url: url, data: {'params': JSON.stringify(params)}, dataType: 'json', cache: false, async: isAsync, timeout: dftTimeOutMilSec, success: function(result){ if (!result.error) { if (successCallback) { successCallback(result.data); } } else { alert('error: ' + result.message); if (failCallback) { failCallback(); } } }, error: function(jqXHR, textStatus, errorThrown){ alert('url: ' + url +', error: ' + textStatus + ", " + errorThrown); if (exceptionCallback) { exceptionCallback(); } } }); } }; async function ajaxPost(url, data) { return new Promise(function (resolve, reject) { $.ajax({ type:"POST", url: url, data: {'data': JSON.stringify(data)}, dataType: 'json', cache: false, timeout: 50000, success: function(result){ if (result.error === 0 ||result.error ===false) { resolve(result.data); } else { alert('error: ' + result.message); reject(result.message); } }, error: function(jqXHR, textStatus, errorThrown){ ajaxErrorInfo(jqXHR, textStatus, errorThrown); reject("请求错误"); } }); }); } function ajaxErrorInfo(jqXHR, textStatus, errorThrown) { if(textStatus == 'timeout'){ alert('网络连接超时,请刷新您的网页。'); }else { alert('url: ' + url +' error ' + textStatus + " " + errorThrown); } }