前言
进行http前后端交互时,由于公司有自己的通用返回参数体,想不再每一次请求后对结果进行判断,这时需要封装一个通用结果处理function,又觉得在回调里渲染比较简单一点,所有又加了个回调,作为一个五手前端,感觉应该把url也加进去的样子
示例
common.js
/**
* 判断请求是否成功获取
* @param res
* @param resultSuccess
*/
var resultValidate = function(res,resultSuccess){
if(res){
if(res.ret == 1){
resultSuccess(res.data);
return ;
}
}
console.log(res)
alert("网络错误,请重试");
}
在请求结果中调用的话,只需要对响应体中的data做处理就好了
new cookieAjax(http_uri,
"get", {},
function (res) {
resultValidate(res,function (data) {
console.log(data);
})
})
这里还对ajax进行了二次封装,具体根据自己的项目进行封装吧
var base_url ;
/**
* 普通ajax
* @param url
* @param type
* @param data
* @param success
* @param error
* @param complete
* @constructor
*/
function Ajax(url,type, data, success, error, complete,contentType){
var dataType = dataType || "json";
var contentType = contentType || "application/x-www-form-urlencoded; charset=utf-8";
$.ajax({
type: type,
url: base_url + url,
data: data,
dataType: dataType,
success: success,
contentType:contentType,
error:error,
complete: complete
});
}
/**
* 携带cookie发起请求
* @param url
* @param type
* @param data
* @param success
* @param error
* @param complete
*/
function cookieAjax(url,type, data, success, error, complete,contentType){
var dataType = dataType || "json";
var contentType = contentType || "application/x-www-form-urlencoded; charset=utf-8";
$.ajax({
type: type,
url: base_url + url,
data: data,
dataType: dataType,
contentType:contentType,
success: success,
error:error,
xhrFields: {
withCredentials: true
},
complete: complete
});
}
-end-











网友评论