URI的编码与解码

对于URI后面的查询字段部分,如何拼接和获取。

编码:
function addURLParam(url,name,value)
{
 url+=(url.indexOf("?") == -1 ? "?" : "&");
 //indexOf取到子串第一次出现的位置
 url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
 return url;
}
解码
var args = getQueryStringArgs();
  function getQueryStringArgs() {    //取得查询字符串并去掉开头的问号
     var qs = (location.search.length > 0 ?        location.search.substring(1) : "");
      //location.search 获取到url问号后的所有查询字符串值,search得到的是url中query部分
      //substring()返回一个从指定位置开始的指定长度的子字符串这里设置为1,是为了把url中的?号去掉
       var args = {};
      //保存数据的对象
      var items = qs.length ? qs.split("&") : [];
      //取得查询字符串中每对键值对,保存到items中
      //split()将一个字符串分割为子字符串,然后将结果作为字符串数组返回这里就是把query部分以&为分割符
      var item = null;
      var name = null;
      var value = null;
      var len = items.length;
      for (var i = 0; i < len; i++) {
      item = items[i].split("=");
      name = decodeURIComponent(item[0]);
      value = decodeURIComponent(item[1]);
      if (name.length) {
                            args[name] = value;
                        }
                    }
                    return args;
                }

ps:  encodeURI 与 encodeURIcomponent
  encodeURI(String)主要用于整个URI(例如,http://www.jxbh.cn/illegal value.htm),而encodeURIComponent(String)主要用于对URI中的某一段(例如前面URI中的value.htm)进行编码。它们的主要区别在于,encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而encodeURIComponent()则会对它发现的任何非标准字符进行编码。

<script type="text/javascript">  

var test1="http://www.wljcz.com/My first/";  
var nn=encodeURI(test1);  
var now=decodeURI(test1);  
document.write(nn+ "<br />");  
document.write(now);  

var test1="http://www.wljcz.com/My first/";  
var bb=encodeURIComponent(test1);  
var nnow=decodeURIComponent(bb);  
document.write(bb+ "<br />");  
document.write(nnow);  

输出:
http://www.wljcz.com/My%20first/
http://www.wljcz.com/My first/
http%3A%2F%2Fwww.wljcz.com%2FMy%20first%2F
http://www.wljcz.com/My first/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值