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一个%,即是三回编码,后台加上自动解码一次也是三次解码

 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值