1.将封装好的ajax()方法放在common.js中。
function ajax(obj) { var type = obj.type || 'post';//请求类型 var dataType = "json";//接收数据类型 var async = obj.async || false;//异步请求 var cache = obj.cache || false;//浏览器历史缓存 var contentType = false; var processData = false; // 成功失败方法 var success = obj.success; var error = obj.error; // 访问地址 var url = obj.url; // 种类 var kind = obj.kind; // 参数 var param1 = obj.param1 || null; var param2 = obj.param2 || null; var param3 = obj.param3 || null; // 传入参数 var data = obj.data || null; if(kind == "1") { data = JSON.stringify(data) contentType = "application/json"; } var success = success || function (result) { console.log(result); alert(result.message); }; var error = error || function (result) { alert(result+"失败") console.log('XMLHttpRequest:'); console.log(XMLHttpRequest); alert('网络异常!尝试刷新网页解决问题') }; if(kind == "3") { $.ajax({ 'url': httpurl+url, 'type': type, 'cache': cache, 'async': async, 'traditional': true, 'data': data, 'success': success, 'error': error }); } else if(kind == '4'){ $.ajax({ 'url': httpurl+url, 'type': type, 'dataType': dataType, 'async': async, 'contentType': contentType, 'data' : data, 'success': success, 'error': error }); } else if(data == 'null') { $.ajax({ 'url': httpurl+url, 'type': type, 'cache': cache, 'dataType': dataType, 'async': async, 'contentType': contentType, 'processData':processData, 'success': function(ret){ if(param1 == null && param2 == null && param3 == null) { success(ret); }else if(param1 != null && param2 == null && param3 == null) { success(ret,param1); }else if(param1 != null && param2 != null && param3 == null) { success(ret,param1,param2); }else if(param1 != null && param2 != null && param3 != null) { success(ret,param1,param2,param3); } }, 'error': error }); } else { $.ajax({ 'url': httpurl+url, 'type': type, 'cache': cache, 'dataType': dataType, 'async': async, 'contentType': contentType, 'processData':processData, 'data': data, 'success': function(ret){ if(param1 == null && param2 == null && param3 == null) { success(ret); }else if(param1 != null && param2 == null && param3 == null) { success(ret,param1); }else if(param1 != null && param2 != null && param3 == null) { success(ret,param1,param2); }else if(param1 != null && param2 != null && param3 != null) { success(ret,param1,param2,param3); } }, 'error': error }); } } // ajax提交(post方式提交) function post(obj) { ajax(obj); }
2.调用ajax
var obj = { "url": "/haha", "data": paramObj,// 无参不用写data属性 "cache": false, "alone": false, "success": hahaSuccess, "kind": "1", // 1 json, 2 form, 3 数组, 4 输入数据格式不转换成json }; post(obj);