javascript中的编码与解码

来源:互联网 发布:西交大网络教育 编辑:程序博客网 时间:2024/04/20 20:13

javascript中可用的编码解码函数,有如下的组合:

  • escape(string);
    unescape(string);
  • encodeURI(string);
    decodeURI(string);
  • encodeURIComponent(string);
    decodeURIComponent(string);

他们之间的区别为:

escape/unescape
16进制编码字符串,对空格、符号等字符用%xx编码表示,对中文等字符用%uxxxx编码表示。自javascript1.5之后,此方法已经不被推荐使用。

encodeURI/decodeURI
UTF-8编码编码字符串,对这些字符:; , /? : @ & = + $ 不做编码。

encodeURIComponent/decodeURIComponent
UTF-8编码编码所有字符串。

因为escape/unescape已经deprecated。就不说它了,encodeURIencodeURIComponent之前的区别用实例说明:

比如说要使用get方式将一个参数u,传递给服务器:

var  u="index.php?blogId=1&op=Default";
var  getURL="http://www.simplelife.cn/test.php?p="+encodeURI(u);


这里,如果使用了encodeURI,那么最终的getURL的值为:

http://www.simplelife.cn/test.php?p=index.php?blogId=1&op=Default


这样,对参数u中的字符"&op=Default",将不会作为字符串参数传递到服务器端,而是当作test.php的参数传递过去了,因为对"&op=Default"中的字符"&"没有做编码。
所以,在这种应用场景下,就需要使用encodeURIComponent,编码后的getURL值为:

http://www.simplelife.cn/test.php?p=index.php%3FblogId%3D1%26op%3DDefault


这样,参数就可以顺利传递过去了。在服务器端得到的字符串将是正确的u

反之,如果需要通过get方式访问某一URL,但是URL中包含中文等字符,为了防止乱码等编码问题,需要将URL通过encodeURI进行编码。

 

原创粉丝点击