jq ajax请求失败、返回code!=0 统一处理方法

请求失败处理

function requesFail(xhr){
	var status = xhr.status;
	if (status) {
	    showNotify("error", "网络错误", "发生网络错误,错误码为:" + xhr.status);
	} else {
	    showNotify("error", "网络错误", "未知网络错误, 请确保设备处在联网状态");
	}
}

请求成功处理

function requestOk(data,errMsg,callbackOk,callbackError){
	if(data==undefined){
		showNotify('info','提示','无法从服务器获取详细数据,请联系管理员')
	}else if(data.code==1){
		callbackOk(data);
	}else{
		callbackError(data,errMsg);
	}
}

*请求成功,返回data:{code:0,data:xx},此处认为code=0,为成功,调用成功后执行

callbackOk

callbackOk 是该请求成功后要进行的操作

code!=0即为出错,执行出错方法:

callbackError

实例:

$('#toPost').click(function(){
		console.log('Post');
		$.ajax({
			type:"Post",
			url:postUrl,
			data:{
				account:'cd',
				password:'121212'
			},
			dataType:'json',
			success:function(data){
				requestOk(data,'',function(){
					console.log(data);
				},customCodeError);
			},
			error:function(xhr,state,errorThrown){
				requesFail(xhr);
			}
		});
	});

customCodeError 为code!=0 要执行的函数:

function customCodeError(data,errMsg){
	let message=errMsg==''?'错误':errMsg+'发生错误';
	message = message + ",错误码为:" + data.code;
	console.log(message);
  	showNotify("info", "错误", msg);
}

若code!=0 ,没有特殊的code=n,需要做特别处理,则调用customCodeError,若有特殊处理,则根据特殊情况,自行封装。

如:

function postCodeError(data,errMsg){
	let code=data.code;
	if(code==1001){
		showNotify("info", "错误", "不合法用户,错误码:"+code);
	}else{
		showNotify("info", "错误", "用户不存在,错误码:"+code);
	}
}

showNotify(),借助pnotify插件的一种显示错误消息的面板。可根据自己的需求进行封装。应用时需导入文件

< link href= "static/css/pnotify.css" rel= "stylesheet" />

< script src= "static/js/common/pnotify.js" > < / script >

/*   notify 配置*  使用
showNotify("info", "提示", "这是提示语句");
showNotify("success", "成功啦", "这是成功语句");
showNotify("error", "失败", "这是失败语句");
*****************************************************************/
function showNotify(type, title, text) {
  var icons;
  if (type == "success") {
    icons = "fa fa-check-circle";
  }
  if (type == "error") {
    icons = "fa fa-exclamation-triangle";
  }
  if (type == "info") {
    icons = "fa fa-exclamation-circle";
  }
  var notice = new PNotify({
    title: title,
    text: text,
    type: type,
    delay: 2000,
    icon: icons,
    addclass: "notifyOnly",
    styling: "fontawesome",
    buttons: {
      closer: true,
      sticker: true
    }
  });
  notice.get().click(function() {
    notice.remove();
  });
}






猜你喜欢

转载自blog.csdn.net/qq_36111804/article/details/80535531