天天看点

URL传值有中文字符怎么处理?

encodeURIComponent(url) 函数

定义和用法 :      encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

语法 :      encodeURIComponent(URIstring)

参数 描述 :      URIstring 必需。一个字符串,含有 URI 组件或其他要编码的文本。

返回值 :      URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

decodeURIComponent(url) 函数

定义和用法 :      decodeURIComponent() 函数可把字符串作为 URI 组件进行解码。

语法 :    decodeURIComponent(URIstring)

参数 描述 :     URIstring 必需。一个字符串,含有 URI 组件或其他要解码的文本。

返回值 :      URIstring 的副本,其中的某些字符被十六进制的转义序列转换成对应的ACSII字符。

例如:

HTML:

<a id="testunicode">编码格式</a>
      

JS:

$("#testunicode").on("click",function () {
    var hanzi = "好好学习";
    var hanzi1 = tounicode(hanzi);
    location.href="${path}/kpijgcx/findKPIList?username=" target="_blank" rel="external nofollow" +hanzi1;
});      
function tounicode(data)
{
    //return encodeURIComponent(data);                    // 编译一次,后台不需要做任何处理
    return encodeURIComponent(encodeURIComponent(data)); //编译了两次,后台需转码
}
      

JAVA:

//username从前台传值过来
System.out.println(username);
String un = java.net.URLDecoder.decode(username,"UTF-8");    //js:encodeURIComponent(encodeURIComponent(data))
System.out.println(un);      

继续阅读