zoukankan      html  css  js  c++  java
  • url字符串和对象之间的转换

    这里会涉及两个需求,有时候,我们想将获得的url字符串按键值对的形式保存成一个对象,用location.search获得url参数字符串,这里不考虑location.pathname和location.hash。

    url字符串对象化

     1 var urlToObj = function (){
     2    var search = this.replace(/^s+|s+$/, '').match(/([^?#]*)(#.*)?$/);     
     3     if( !search ){
     4         return {};     
     5     }
     6      
     7     var searchHash = search[1].split('&');
     8     var obj = {};
     9     
    10     for(var i = 0, len = searchHash.length; i<len; i++){
    11          var pair = searchHash[i].split('=');
    12          if(pair[0]){
    13             var key = decodeURIComponent(pair[0]);
    14             var value = pair[1];
    15             if(value != undefined ){
    16                 value = decodeURICoponent(value);
    17             }
    18             //这里判断转化后的obj里面有没有重复的属性
    19             if( key in obj ){
    20                 if( obj [key] != Array ){
    21                     //把属性值变为数组,将另外的属性值也存放到数组中去
    22                     obj [key] = [obj [key]];
    23                 }
    24                 obj [key].push(value);
    25             }else{
    26                  obj [key] = value;
    27             }
    28          }
    29     }
    30 
    31     return obj;
    32 };          
    33 
    34 //调用可以如下
    35  urlToObj.call( location.search );                 
  • 相关阅读:
    getJson
    mongodb在java中的查询
    Fragment
    android权限
    json输出
    Android Service
    javascript
    android
    Myeclipse启动报错: Invalid 'log4jConfigLocation' parameter
    Android-Activity生命周期
  • 原文地址:https://www.cnblogs.com/guoyongfeng/p/3902945.html
Copyright © 2011-2022 走看看