JS中encodeURIComponent(URL)编码与decodeURIComponent(URL)解码详解
来源:互联网 发布:茅台防伪溯源软件下载 编辑:程序博客网 时间:2024/06/05 14:58
(1) encodeURIComponent(url) 函数
定义和用法
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
语法
encodeURIComponent(URIstring)
参数 描述
URIstring 必需。一个字符串,含有 URI 组件或其他要编码的文本。
返回值
URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
说明
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序
列替换的。
(1) decodeURIComponent(url) 函数
定义和用法
decodeURIComponent() 函数可把字符串作为 URI 组件进行解码。
语法
decodeURIComponent(URIstring)
参数 描述
URIstring 必需。一个字符串,含有 URI 组件或其他要解码的文本。
返回值
URIstring 的副本,其中的某些字符被十六进制的转义序列转换成对应的ACSII字符。
今天在使用js的jQuery的post向后台servlet传递拼接的字符串数据时,一些特殊的字符例如:“+、@、#、
$、%、&、?、/”等无法传递到后台输出。
举个例子:
var str1="a+aa+bb@kk$dd";
var data="data1"="+str1+"+"&"+"data2"+str2;
如果不进行编码,则通过js的jQuery的post或者使用window.self.location传递数据到后台,都会造成+、
@、$字符无法正常输出。
正确写法:
var str1=encodeURIComponent("a+aa+bb@kk$dd");
var data="data1"="+str1+"+"&"+"data2"+str2;
对于使用window.self.location传递数据到后台时,有一个特殊情况,就是Java中的解码方式:
JavaScript用encodeURIComponent编码后无法再到后台解码的问题。
目前写法:
window.self.location="index.jsp?data="+encodeURIComponent(url);
java处理的代码为:
searchtext=java.NET.URLDecoder.decode(searchtext,"UTF-8");
咋一看觉的没问题,一编一解的,应该可以了。但还是出现了乱码。
原因:
原来在对后台java程序里的data赋值的时候,本身已经使用了一次解码,不过解码的结果依然不对。所以我们
可以在页面上进行两次编码操作,这样后台自动的那次就可以抵消掉一次,然后在使用
data=java.Net.URLDecoder.decode(data,"UTF-8");进行一次解码就好了。
正确的代码:
JavaScript:
window.self.location="index.jsp?data="+encodeURIComponent(encodeURIComponent(url));
java:
searchtext=java.net.URLDecoder.decode(data,"UTF-8");
另外还有一种方法是JavaScript进行一次编码,后台java处理时换种想法就好了:
java代码:
String s = new String(request.getParameter("data").getBytes("ISO8859-1"), "UTF-8");
- JS中encodeURIComponent(URL)编码与decodeURIComponent(URL)解码详解
- JS中encodeURIComponent(URL)编码与decodeURIComponent(URL)解码详解
- JS中encodeURIComponent(URL)编码与decodeURIComponent(URL)解码详解
- js url编码解码函数 decodeURIComponent encodeURIComponent
- URL编码(encodeURIComponent和decodeURIComponent)
- JS----编码,解码decodeURIComponent,encodeURIComponent,decodeURI,encodeURI
- URL转码 js decodeURIComponent encodeURIComponent 函数
- 【js】javascript中url编码与解码
- JS中URL编码与.net URL解码 (待分析出错原因)
- JS中URL编码与.net URL解码
- JS中URL编码与.net URL解码
- JS中URL编码与.net URL解码
- JS中URL编码与.net URL解码
- js中的编码解码--escape/unescape、encodeURI/decodeURI 、encodeURIComponent/decodeURIComponent
- js中使用encodeURIComponent编码url后java后台的解码
- JS 字符串编码函数(解决URL特殊字符传递问题):escape()、encodeURI()、encodeURIComponent()区别详解
- URL编码与解码(特殊字符)
- (转载)URL编码与解码
- 线程间的读写锁
- hibernate配置文件hibernate.cfg.xml的详细解释
- 你知道亚媒的来源么?
- PHP字符串比较
- 在LuisDialog中使用PromptDialog
- JS中encodeURIComponent(URL)编码与decodeURIComponent(URL)解码详解
- (1)红帽认证
- 图像卷积与滤波的一些知识点
- Caused by: org.apache.ibatis.binding.BindingException: Parameter 'offset' not found. Available param
- mysql主从配置(清晰的思路 主win7--从Linux)
- excel公式
- JavaScript编程中的同步与异步机制
- Deep Learning for OCR
- CABasicAnimation animationWithKeyPath 一些规定的值