关于URL编码

基本概念

1.encodeComponent编码url,url不能直接运用,须要编码

var rlt = "http://service.weibo.com/share/share.php?";
var url = 'http://www.baidu.com';
var params = {
    appkey: "379570494",
    title: "领杉果红包,享更多优惠!点击领取:",
    url: url
};
for (var i in params) {
    rlt += i + '=' + params[i] + '&';
}
for (var i in params) {
    rlt += i + '=' + encodeURIComponent(params[i]) + '&';
}
console.log(rlt);

题目的由来

1.URL就是网址,只需上网,就一定会用到.
只要字母和数字[0-9a-zA-Z],一些特别标记$-_.+!*'(),以及某些保留字,才能够不经由编码直接用于URL.
2.这意味着,假如URL中有汉字,就必须编码后运用,然则贫苦的是,RFC1738没有划定详细的编码方法,
而是交给应用程序(浏览器)本身决议,这致使’URL编码’成为了一个杂沓的范畴.
3.包括:ajax要求url地点,浏览器上直接用get或post发出http要求,网址途径中包括汉字,查询字符串包括汉字.
4.运用js先对URL编码,然后再向服务器提交,不给浏览器加入的时机,
由于js的输出老是一致的,所以就保证了服务器获得的数据是花样一致的.

escape,unescape

escape()不能直接用于URL编码,他的真正作用是返回一个字符串的Unicode编码值.

encodeURI和decodeURI

1.encodeURI()是js中真正用来对URL编码的函数
2.它着眼于对全部URL举行编码,因而除了罕见的标记之外,对其他一些在网址中有特别寄义的标记;/?:@&=+$,#也不举行编码,
编码后,它输出标记的utf-8情势,并且在每一个字节前加上%

encodeURIComponent和decodeURIComponent

与encodeURI()的区别是,它用于对URL的组成部分举行一般编码,而不用于对全部URL举行编码.
因而,;/?:@&=+$,#这些在encodeURI()中不被编码的标记,在encodeURIComponent中一切会被编码.

var test = 'http://www.baidu.com/my app?search=a&b=3#2哈哈';
var test1 = encodeURIComponent(test);
var test2 = encodeURI(test);
console.log(test);  // http://www.baidu.com
console.log(test1); // http%3A%2F%2Fwww.baidu.com%2Fmy%20app%3Fsearch%3Da%26b%3D3%232%E5%93%88%E5%93%88,浏览器没法剖析这个地点
console.log(test2); // http://www.baidu.com/my%20app?search=a&b=3#2%E5%93%88%E5%93%88,浏览器没法剖析这个地点

var test3 = decodeURIComponent(test1);
var test4 = decodeURI(test2);
console.log(test3);
console.log(test4);

var test5 = escape(test);
var test6 = unescape(test5);
console.log(test5); // http%3A//www.baidu.com/my%20app%3Fsearch%3Da%26b%3D3%232%u54C8%u54C8
console.log(test6); // http://www.baidu.com/my app?search=a&b=3#2哈哈
    原文作者:蛋白
    原文地址: https://segmentfault.com/a/1190000010375983
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞