1

I'm trying to figure out how to enable the back and forward buttons in my AJAX application, which is dynamic and database driven. To capture the state, I am trapping some values for url, type, and data in an associative array.

I am getting the hash string back from the browser during the 'hashchange' event, I just don't know how to turn it back into an associative array from the encoded query string. Can anybody help?

James Allardice
  • 164,175
  • 21
  • 332
  • 312
RubyRedGrapefruit
  • 12,066
  • 16
  • 92
  • 193
  • possible duplicate of [The $.param( ) inverse function in JavaScript / jQuery](http://stackoverflow.com/questions/1131630/the-param-inverse-function-in-javascript-jquery) – Qantas 94 Heavy Mar 15 '14 at 01:19

4 Answers4

6

something like this?

var hash = 'one=1&two=2',
    split = hash.split('&');

var obj = {};
for(var i = 0; i < split.length; i++){
    var kv = split[i].split('=');
    obj[kv[0]] = decodeURIComponent(kv[1] ? kv[1].replace(/\+/g, ' ') : kv[1]);
}
console.log(obj);
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • Josiah, that is almost on the money, but the values I serialized have pluses in them for the spaces, etc., and have been encoded for submission. The jQuery deserialize plugin is working, except that I can't now decode some of the values. – RubyRedGrapefruit Feb 28 '11 at 01:50
  • @AKWF - I updated the fiddle and the post to decode, and replace `+` characters. – Josiah Ruddell Feb 28 '11 at 04:42
  • I ended up finding the URL Decoder plugin. It worked right away, some of the internals are probably almost identical with what you did here. Thanks for your help Josiah. – RubyRedGrapefruit Feb 28 '11 at 14:46
2

jQuery has a deserialize plugin that might fit the bill.

Alternatively take a look at this SO answer which writes a jQuery function to do the same.

Community
  • 1
  • 1
Chris Van Opstal
  • 36,423
  • 9
  • 73
  • 90
2
function getQuery() {
    var query = window.location.hash.substring(1);
    var queryArray = [];
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        queryArray.push([pair[0], pair[1]);
    }
    return queryArray;
}
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
0

Thanks guys. It looks like a call to $.bbq.getState() does most of it for me. But I will need that deserialize method later...

RubyRedGrapefruit
  • 12,066
  • 16
  • 92
  • 193