2009-08-05 56 views
5

後存儲數據我想散後,在URI的鍵/值對存儲在客戶端使用,像這樣:URI中的哈希

http://www.foo.com/index.html#foo=bar&baz=quux 

是否有預先存在的解決方案,它已經這樣做或我應該推出自己的?我已經在使用JQuery,所以JQuery解決方案特別受歡迎。

我最初的想法是使用正則表達式,但這會變得複雜,特別是當您添加需要同時轉義鍵和值時。

編輯:讓我澄清。我想要做這樣的事情:

foo = hash.get('foo'); 
hash.set('bar','baz'); 

回答

7

任何有興趣,這裏是我想出瞭解決方案:

/** 
* Copyright 2009 by David Kerkeslager 
* Released under the BSD License (http://davidkerkeslager.com/license.txt). 
* 
* This library defines an object-literal which allows one to store key/value pairs after the hash (#) in the URI. 
* The syntax of the storage is modeled after the way that GET variables are stored after the question mark (?) in 
* the URI. 
* 
* Example URI: "http://www.foo.com/index.html#foo=bar&baz=quux" 
* 
* Note: it should be obvious that this should not be used for storing private data of any kind. 
*/ 

var URIHash = 
{ 
    /** 
    * Dump the contents of the URI hash into an associative array. If the hash is invalid, the method returns 
    * undefined. 
    */ 
    dump : function() 
    { 
     var hash = document.location.hash; 
     var dump = new Array(); 

     if(hash.length == 0) return dump; 

     hash = hash.substring(1).split('&'); 

     for(var key in hash) 
     { 
      var pair = hash[key].split('='); 

      if(pair.length != 2 || pair[0] in dump) 
       return undefined; 

      // escape for storage 
      dump[unescape(pair[0])] = unescape(pair[1]); 
     } 

     return dump; 
    }, 

    /** 
    * Takes an associative array and stores it in the URI as a hash after the # prefix, replacing any pre- 
    * existing hash. 
    */ 
    load : function(array) 
    { 
     var first = true; 
     var hash = ''; 

     for(var key in array) 
     { 
      if(!first) hash += '&'; 
      hash += escape(key) + '=' + escape(array[key]); 
     } 

     document.location.hash = hash; 
    }, 

    /** 
    * Get the value of a key from the hash. If the hash does not contain the key or the hash is invalid, 
    * the function returns undefined. 
    */ 
    get : function(key) 
    { 
     return this.dump()[key]; 
    }, 

    /** 
    * Set the value of a key in the hash. If the key does not exist, the key/value pair is added. 
    */ 
    set : function(key,value) 
    { 
     var dump = this.dump(); 
     dump[key] = value; 

     var hash = new Array(); 

     for(var key in dump) 
      hash.push(escape(key) + '=' + escape(dump[key])); 

     document.location.hash = hash.join('&'); 
    } 
} 
1

您可以在散列之後存儲JSON數據。我一直在考慮這樣做 - 它會避免解析,儘管你可能會打開自己的篡改。

+0

這是一個有點重量級不是我想要的;鍵/值對都是必需的。但是,如果沒有更清潔的選擇,我可能會考慮這一點,只是爲了能夠使用預先包裝的選項。我們拭目以待。 – Imagist 2009-08-05 23:33:22