码迷,mamicode.com
首页 > 其他好文 > 详细

encodeURI和encodeURIComponent的比较

时间:2014-09-08 10:46:36      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   java   ar   strong   

  encodeURI和encodeURIComponet函数都是javascript中用来对URI进行编码,将相关参数转换成UTF-8编码格式的数据。URI在进行定位跳转时,参数里面的中文、日文等非ASCII编码都会进行编码转换。

例如:

var str1 = "http://www.baidu.com/s?wd=中国&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526";
window.location.href=str1;

  上面的uri里面包含中文,浏览器解析时无法识别,不能直接跳转。需要进行转码!

 

1、encodeURI:该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ‘ ( ) 。 URI 中具有特殊含义的 ASCII 标点符号,如:;/?:@&=+$,# 也不会进行转码。

  前面的例子,采用encodeURI转码方式如下:

var str1 = encodeURI("http://www.baidu.com/s?wd=中国&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526");
window.location.href=str1;

  转码后的内容如下:

http://www.baidu.com/s?wd=%E4%B8%AD%E5%9B%BD&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526

      

2、encodeURIComponet:该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ‘ ( ) 。其他它字符(包括 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号)都会进行转码。

  前面的例子,采用encodeURIComponet转码方式如下:

var str1 = "http://www.baidu.com/s?wd="+encodeURIComponent("中国")+"&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526";
window.location.href=str1;

  转换后的内容如下:

http://www.baidu.com/s?wd=%E4%B8%AD%E5%9B%BD&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526

  如果使用encodeURIComponet进行整体转码。由于将&等字符也将被转换,导致浏览器无法解析跳转失败。

var str1 = encodeURIComponent("http://www.baidu.com/s?wd=中国&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2526");
window.location.href=str1;
http%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%E4%B8%AD%E5%9B%BD%26rsv_spt%3D1%26issp%3D1%26rsv_bp%3D0%26ie%3Dutf-8%26tn%3Dbaiduhome_pg%26inputT%3D2526

 

  总结:(1)encodeURI的目的是对 URI 进行整体编码,故适用于url跳转时使用;(2)encodeURIComponent会把部分uri关键字符(如:&等)也进行转换,故适用于传递参数时使用。

encodeURI和encodeURIComponent的比较

标签:style   blog   http   color   io   使用   java   ar   strong   

原文地址:http://www.cnblogs.com/mistwalker/p/3961114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!