3

Currently I use page numbers in hashes with Ben's Alman jquery-hashchange plugin:

$(document).ready(function(){
    $(window).hashchange( function(){
      var hash = (location.hash) ? location.hash.slice(1) : 'page1';
      $.ajax({
          url: '/list/' + hash, // result url like page1, page2 etc.

Now I need to add there one more value - filter. I think result hash URL can look like

#page1&filter=1-1-0 
#filter=1-1-0 (if page number is omitted)
#page1 (if filter is not defined)

How to parse that? I.e. how to understand if page is defined, if filter is defined (and what are the values - 1, 1 and 0 - I need them separately)?

I was thinking about Ben's Alman BBQ plugin, but (1) it looks too complicated for such simple task, (2) not sure how to use parameters (page1, page2 etc.) without values.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
LA_
  • 19,823
  • 58
  • 172
  • 308

1 Answers1

5

Very simple and unextediable parser for two hardcoded variables:

var hash_parts = location.hash.split('&', 2); //2 - limit, may be changed if more than two arguments

for(i in hash_parts) {
    if(hash_parts[i].indexOf("page") === 0) { //begins with "page"
        var current_page_number = hash_parts[i].substr(4);
    }
    else if(hash_parts[i].indexOf("filter") === 0) { //begins with "filter"
        var filter = hash_parts[i].split('=', 2);
        var filer_values = filter[1].split('-'); //filter_values == {'1', '1', '0'}
    }
}

You can easily make it universal.

Please, also take a look here: Parse query string in JavaScript - just change window.location.search.substring(1) to hash.

Community
  • 1
  • 1
Oroboros102
  • 2,214
  • 1
  • 27
  • 41
  • Thanks! Another task I should resolve is how to define such hashes with javascript (i.e. I should understand if parameter is already added and if so, then I need to modify its value; otherwise - add parameter). – LA_ Nov 05 '11 at 16:05
  • Manipulating hash is easy `document.location.hash = "somehash";`. So, you can do like that: `if(document.location.hash.length > 0) { ... do something... }`. – Oroboros102 Nov 08 '11 at 14:29
  • Actually it is not so easy as you need to identify if some parm is already there and if so, then just update its value, otherwise - add it. I've used Ben's Alman BBQ plugin for the same. – LA_ Nov 08 '11 at 15:50