ajax传参后台接收防止中文乱码,一次两次encode,decode都可

1.前台ajax,注意data参数的一次encode

function checkCode(){
	    	
	       $.ajax({ 
	            async:false,
	            type:'get',
				url: 'business/admin/isExistsCheckItem.html',
				data:{cid:-1, checkname:encodeURI($("#checkname").val())},
				dataType:'json',
				success: function(data) {
				     var info = eval("("+data+")");
				     if (info.res){
				         flag = true;
				     }else{
				         flag = false;
				     }
				},
				error: function(){                         
		           alert('检验项目名称出错!');    
		        }
			});
	    }

后台ssh框架的action函数,注意一次解码decode,打印得到前台的中文“你好”

public String isExists() throws UnsupportedEncodingException {
		String checkname1 = URLDecoder.decode(request.getParameter("checkname"),"UTF-8");
		//String checkname2=URLDecoder.decode(checkname1,"UTF-8");
		System.out.println(checkname1);
    	if (checkItemService.isExists(cid,checkname1)!=-1){
			info = "{res:true}";
			return "exists";
		}
     	info = "{res:false}";
    	return "exists";  
    }

此处,其实在我们发送URL的时候,浏览器帮我们转码了一次,因此前台发送时路径是http://localhost:8080/libbms/business/admin/business/admin/isExistsCheckItem.html?cid=-1&checkname=%25E4%25BD%25A0%25E5%25A5%25BD%25E5%2595%258A

路径数字25的Unicode编码即是%,所以是两次编码,同理后台接收会自动解码一次, 再手动解码一次即可恢复原本传的中文(这个道理可以想一下什么都不做,url中文会自动变成一堆十六进制数)

2.再看两次编码解码的情况,很多博客写的也是这种两次encode,decode的情况

注意下面代码的两个encodeURI

 function checkCode(){
	       $.ajax({
	            async:false,
	            type:'get',
				url: 'business/admin/isExistsLabProcess.html',
				data:{cid:-1, labprocesstitle:encodeURI(encodeURI($("#labprocesstitle").val()))},
				dataType:'json',
				
				success: function(data) {
				     var info = eval("("+data+")");
				     if (info.res){
				         flag = true;
				         
				     }else{
				         flag = false;
				        
				     }
				},
				error: function(){                         
		           alert('实验过程标题出错!');    
		        }
			});
	    }

 后台同理,注意两次解码,也能防止中文乱码得到想要的中文

public String isExists() throws UnsupportedEncodingException{
		String labprocesstitle1 = URLDecoder.decode(request.getParameter("labprocesstitle"),"UTF-8");
		String labprocesstitle2=URLDecoder.decode(labprocesstitle1,"UTF-8");
		
    	if (labProcessService.isExists(cid,labprocesstitle2)!=-1){   		
			info = "{res:true}";    //有
			return "exists";
		}
     	info = "{res:false}";
    	return "exists";  
    }

这是输入中文后的路径,

Request URL:

http://localhost:8080/libbms/business/admin/business/admin/isExistsLabProcess.html?cid=-1&labprocesstitle=%2525E4%2525BD%2525A0%2525E5%2525A5%2525BD%2525E5%252590%252597

 两个25一个%,即是三回编码,后台加上自动解码一次也是三次解码

欢迎各位大佬指正,萌新谢过!

发布了30 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40898368/article/details/86619515
今日推荐