[WEB开发]html页面向后台传递url中文乱码解决方案

开发中常遇到页面向action或service传递url,并通过url传递中文参数问题,尤其是表单提交。而由于表单内容文本的编码是根据浏览器的规则,因此,在传递的时候常出现中文乱码的情况,以下给出解决方案:

 在js中将中文信息进行编码如url = encodeURI(url);,此时action或service得到的将%23%3E%3……此类的文本,但由于浏览器把%误认为转义字符,因此解决方案为套两层编码,如url = encodeURI(encodeURI(url));

 之后在action或是service中使用url=URLDecoder.decode(url, "UTF-8");即可完美解决中文乱码问题。此方法类似密码学中的加密和解密过程。
一、传多个参数
   let urlName = "/html/h.html?type=init&city="+ this.cityName +"&province=" + this.provinceName;
  let url = encodeURI(encodeURI(urlName));
  web-view 跳转(:src="url")
  html页里接收
  var url = location.search; 
this.theRequest = {};
  
if (url.indexOf("?") != -1) {
	let str = url.substr(1);
	let strs = str.split("&");
	for (var i = 0; i < strs.length; i++) {
		this.theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
	}

	// let typeName = this.theRequest["type"];
	// console.log('type==========',decodeURI(typeName))
	// let cityName = this.theRequest["city"];
	// console.log('city============',decodeURI(cityName))
	// let province = this.theRequest["province"];
	// console.log('province==========',decodeURI(province))
            }
decodeURI(typeName)
二、传对象
let lArguments = {
        type: "init他那",
        city: this.cityName,
        province: this.provinceName
      }
			let urlName = "../../hybrid/html/hBegin.html?opt="+ JSON.stringify(lArguments);
	let url = encodeURI(encodeURI(urlName));  
	web-view 跳转(:src="url")
	html页里接收
	// let opt = this.theRequest["opt"];
	// console.log('opt==========',decodeURI(opt))
	// let aObject =JSON.parse(decodeURI(opt)) ;
	// console.log('type--->>'+ aObject["type"])
	// console.log('city--->>'+ aObject["city"])
	// console.log('province--->>'+ aObject["province"])
	
encodeURIComponent
decodeURIComponent
posted @ 2021-12-23 15:50  寒冷的雨呢  阅读(697)  评论(1编辑  收藏  举报